### Build Example and Validate Generated Code Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/contributing.md Builds the example application, generates API code, and validates the generated code. This command ensures the codegen process works correctly for the example project. ```bash npm run build && pnpm --filter @7nohe/react-app generate:api && pnpm --filter @7nohe/react-app test:generated ``` -------------------------------- ### Preview Documentation Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/contributing.md Starts a development server to preview the project's documentation locally using pnpm. ```bash pnpm --filter docs dev ``` -------------------------------- ### Install the package Source: https://context7.com/7nohe/openapi-react-query-codegen/llms.txt Add the generator as a development dependency to your project. ```bash npm install -D @7nohe/openapi-react-query-codegen ``` -------------------------------- ### Install Dependencies Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/contributing.md Installs project dependencies using pnpm. Ensure Node.js v20.16.0 or later and pnpm v9 are installed. ```bash pnpm install ``` -------------------------------- ### Run Development Server with npm Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/examples/nextjs-app/README.md Use this command to start the Next.js development server with npm. The server will auto-update as you edit files. ```bash npm run dev ``` -------------------------------- ### Install OpenAPI React Query Codegen Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/guides/introduction.mdx Install the package as a development dependency using your preferred package manager. ```bash npm install -D @7nohe/openapi-react-query-codegen ``` ```bash yarn add -D @7nohe/openapi-react-query-codegen ``` ```bash pnpm add -D @7nohe/openapi-react-query-codegen ``` -------------------------------- ### Run Development Server with Bun Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/examples/nextjs-app/README.md Use this command to start the Next.js development server with Bun. The server will auto-update as you edit files. ```bash bun dev ``` -------------------------------- ### Run Development Server with Yarn Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/examples/nextjs-app/README.md Use this command to start the Next.js development server with Yarn. The server will auto-update as you edit files. ```bash yarn dev ``` -------------------------------- ### Run Development Server with pnpm Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/examples/nextjs-app/README.md Use this command to start the Next.js development server with pnpm. The server will auto-update as you edit files. ```bash pnpm dev ``` -------------------------------- ### Install TanStack Query Dependencies Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/guides/introduction.mdx Install the required TanStack Query package for the generated hooks to function. ```bash npm install @tanstack/react-query ``` ```bash yarn add @tanstack/react-query ``` ```bash pnpm add @tanstack/react-query ``` -------------------------------- ### Next.js App Router Provider Setup Source: https://context7.com/7nohe/openapi-react-query-codegen/llms.txt Configure QueryClient for Next.js App Router with SSR support. This setup ensures proper client instantiation on both server and browser environments. ```tsx // app/providers.tsx "use client"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { client } from "./openapi/requests/services.gen"; // Configure API client client.setConfig({ baseUrl: process.env.NEXT_PUBLIC_API_URL || "http://localhost:4010", }); function makeQueryClient() { return new QueryClient({ defaultOptions: { queries: { // Prevent immediate refetch on client after SSR staleTime: 60 * 1000, }, }, }); } let browserQueryClient: QueryClient | undefined = undefined; function getQueryClient() { if (typeof window === "undefined") { // Server: always create a new client return makeQueryClient(); } // Browser: reuse existing client if (!browserQueryClient) browserQueryClient = makeQueryClient(); return browserQueryClient; } export default function Providers({ children }: { children: React.ReactNode }) { const queryClient = getQueryClient(); return ( {children} ); } // app/layout.tsx import Providers from "./providers"; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` -------------------------------- ### Customize `useQuery` with Pure TypeScript Client Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/guides/usage.mdx Optionally, use the pure TypeScript client for custom query configurations. The SDK functions are available via `openapi/requests/sdk.gen.ts` or the shim `openapi/requests/services.gen.ts`. This example shows how to use `@tanstack/react-query`'s `useQuery` with auto-generated query keys. ```tsx import { useQuery } from "@tanstack/react-query"; import { findPets } from "../openapi/requests/services.gen"; import { useFindPetsKey } from "../openapi/queries"; function App() { // You can still use the auto-generated query key const { data } = useQuery({ queryKey: [useFindPetsKey], queryFn: () => { // Do something here return findPets(); }, }); return
{/* .... */}
; } export default App; ``` -------------------------------- ### Configure QueryClient and Interceptors Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/guides/introduction.mdx Set up the QueryClientProvider and configure the API client base URL and interceptors. ```tsx // src/main.tsx import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; import { QueryClientProvider, QueryClient } from "@tanstack/react-query"; // services.gen.ts is a backward-compatibility shim that re-exports from client.gen and sdk.gen import { client } from "../openapi/requests/services.gen"; client.setConfig({ baseUrl: "YOUR_BASE_URL", throwOnError: true, // If you want to handle errors on `onError` callback of `useQuery` and `useMutation`, set this to `true` }); client.interceptors.request.use((config) => { // Add your request interceptor logic here return config; }); client.interceptors.response.use((response) => { // Add your response interceptor logic here return response; }); export const queryClient = new QueryClient(); ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( ); ``` -------------------------------- ### Configure the API client Source: https://context7.com/7nohe/openapi-react-query-codegen/llms.txt Set up the base URL and request/response interceptors for the generated client before initializing the application. ```tsx // src/main.tsx import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; import { QueryClientProvider, QueryClient } from "@tanstack/react-query"; import { client } from "./openapi/requests/services.gen"; // Configure the API client client.setConfig({ baseUrl: "https://api.example.com", throwOnError: true, // Required for error handling in useQuery/useMutation onError callbacks }); // Add request interceptor for authentication client.interceptors.request.use((config) => { const token = localStorage.getItem("authToken"); if (token) { config.headers = { ...config.headers, Authorization: `Bearer ${token}`, }; } return config; }); // Add response interceptor for error logging client.interceptors.response.use((response) => { if (!response.ok) { console.error(`API Error: ${response.status} ${response.statusText}`); } return response; }); export const queryClient = new QueryClient(); ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( ); ``` -------------------------------- ### Run Tests Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/contributing.md Executes the project's test suite using pnpm. ```bash pnpm test ``` -------------------------------- ### Use Generated `useQuery` Hooks Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/guides/usage.mdx Import and use the generated `useFindPets` hook to fetch data. Ensure the path to the generated queries is correct. ```tsx import { useFindPets } from "../openapi/queries"; function App() { const { data } = useFindPets(); return (

Pet List

); } export default App; ``` -------------------------------- ### Implement useInfiniteQuery for Pagination Source: https://context7.com/7nohe/openapi-react-query-codegen/llms.txt Handle paginated data fetching with infinite scrolling support using generated infinite query hooks. ```tsx import React from "react"; import { useFindPaginatedPetsInfinite } from "./openapi/queries/infiniteQueries"; function InfinitePetList() { const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading, error, } = useFindPaginatedPetsInfinite({ query: { tags: [], limit: 10 }, }); if (isLoading) return
Loading...
; if (error) return
Error: {error.message}
; return (
{hasNextPage && ( )} {!hasNextPage &&

No more pets to load

}
); } ``` -------------------------------- ### Execute Codegen Script Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/guides/introduction.mdx Run the configured codegen script to generate hooks. ```bash npm run codegen ``` ```bash yarn codegen ``` ```bash pnpm codegen ``` -------------------------------- ### Run Linter and Fix Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/contributing.md Executes the linter and automatically fixes any detected code style issues using pnpm. ```bash pnpm lint:fix ``` -------------------------------- ### Generate code via CLI Source: https://context7.com/7nohe/openapi-react-query-codegen/llms.txt Execute the CLI to generate hooks from an OpenAPI schema file with various configuration options. ```bash # Basic usage - generates code in ./openapi directory npx openapi-rq -i ./petstore.yaml # Custom output directory npx openapi-rq -i ./petstore.yaml -o ./src/api # Use axios client instead of fetch npx openapi-rq -i ./petstore.yaml -c @hey-api/client-axios # Format output with Prettier npx openapi-rq -i ./petstore.yaml --format prettier # Lint output with ESLint npx openapi-rq -i ./petstore.yaml --lint eslint # Generate TypeScript enums npx openapi-rq -i ./petstore.yaml --enums typescript # Configure pagination parameters npx openapi-rq -i ./petstore.yaml --pageParam page --nextPageParam nextPage --initialPageParam 1 # Remote OpenAPI spec URL npx openapi-rq -i https://api.example.com/openapi.json # Run without installing npx --package @7nohe/openapi-react-query-codegen openapi-rq -i ./petstore.yaml ``` -------------------------------- ### Run Linter Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/contributing.md Runs the linter to check for code style issues using pnpm. ```bash pnpm lint ``` -------------------------------- ### Package.json Scripts for Code Generation Source: https://context7.com/7nohe/openapi-react-query-codegen/llms.txt Configure npm scripts for the code generation workflow, including watch mode, remote OpenAPI spec generation, and pre-build hooks. ```json { "scripts": { "codegen": "openapi-rq -i ./openapi/petstore.yaml -o ./src/api", "codegen:watch": "nodemon --watch ./openapi -e yaml --exec 'npm run codegen'", "codegen:remote": "openapi-rq -i https://api.example.com/openapi.json -o ./src/api", "codegen:formatted": "openapi-rq -i ./openapi/petstore.yaml --format prettier --lint eslint", "prebuild": "npm run codegen" }, "devDependencies": { "@7nohe/openapi-react-query-codegen": "^2.1.0" }, "dependencies": { "@tanstack/react-query": "^5.0.0", "@hey-api/client-fetch": "^0.1.0" } } ``` -------------------------------- ### Configure Codegen Script Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/guides/introduction.mdx Add the codegen command to your package.json scripts to simplify execution. ```json { "scripts": { "codegen": "openapi-rq -i ./petstore.yaml" } } ``` -------------------------------- ### Implement useSuspenseQuery for Declarative Loading Source: https://context7.com/7nohe/openapi-react-query-codegen/llms.txt Utilize Suspense-enabled hooks to handle loading states declaratively with React Suspense and ErrorBoundary. ```tsx import { Suspense } from "react"; import { ErrorBoundary } from "react-error-boundary"; import { useFindPetsSuspense } from "./openapi/queries/suspense"; // Child component with suspense hook - data is guaranteed to be available function PetListContent() { const { data } = useFindPetsSuspense({ query: { tags: [], limit: 10 }, }); // No need to check for loading or undefined - Suspense handles it return ( ); } // Error fallback component function ErrorFallback({ error, resetErrorBoundary }) { return (

Something went wrong: {error.message}

); } // Parent component with Suspense and ErrorBoundary function PetList() { return ( Loading pets...}> ); } ``` -------------------------------- ### Implement Prefetching for SSR in Next.js Source: https://context7.com/7nohe/openapi-react-query-codegen/llms.txt Use prefetch functions in Next.js Server Components to hydrate data on the client side. ```tsx // app/page.tsx (Next.js Server Component) import { HydrationBoundary, QueryClient, dehydrate, } from "@tanstack/react-query"; import { prefetchUseFindPets } from "./openapi/queries/prefetch"; import PetList from "./components/PetList"; export default async function HomePage() { const queryClient = new QueryClient(); // Prefetch data on the server await prefetchUseFindPets(queryClient, { query: { tags: [], limit: 10 }, }); // Dehydrate state for client hydration return ( ); } // app/components/PetList.tsx (Client Component) "use client"; import { useFindPets } from "../openapi/queries"; export default function PetList() { // Data is immediately available from prefetch - no loading state on initial render const { data } = useFindPets({ query: { tags: [], limit: 10 }, }); return ( ); } ``` -------------------------------- ### Use Generated `useQuerySuspense` Hooks Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/guides/usage.mdx Utilize `useFindPetsSuspense` for suspense-enabled data fetching. This hook requires a `Suspense` boundary in the parent component to handle loading states. ```tsx import { useFindPetsSuspense } from "../openapi/queries/suspense"; function ChildComponent() { const { data } = useFindPetsSuspense({ query: { tags: [], limit: 10 }, }); return ; } function ParentComponent() { return ( <> loading...}> ); } function App() { return (

Pet List

); } export default App; ``` -------------------------------- ### Define Paginated Endpoint in OpenAPI Schema Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/guides/usage.mdx Configure the path with query parameters for pagination and a response object containing the next page indicator. ```yaml paths: /paginated-pets: get: description: | Returns paginated pets from the system that the user has access to operationId: findPaginatedPets parameters: - name: page in: query description: page number required: false schema: type: integer format: int32 - name: tags in: query description: tags to filter by required: false style: form schema: type: array items: type: string - name: limit in: query description: maximum number of results to return required: false schema: type: integer format: int32 responses: '200': description: pet response content: application/json: schema: type: object properties: pets: type: array items: $ref: '#/components/schemas/Pet' nextPage: type: integer format: int32 minimum: 1 ``` -------------------------------- ### Generated Directory Structure Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/guides/introduction.mdx The file structure created after running the codegen command. ```bash $ tree openapi openapi/ ├── queries │ ├── common.ts │ ├── ensureQueryData.ts │ ├── index.ts │ ├── infiniteQueries.ts │ ├── prefetch.ts │ ├── queries.ts │ └── suspense.ts └── requests ├── client/ ├── core/ ├── client.gen.ts ├── index.ts ├── sdk.gen.ts ├── services.gen.ts └── types.gen.ts ``` -------------------------------- ### Use Generated `useMutation` Hooks Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/guides/usage.mdx Import and use the generated `useAddPet` hook to perform mutations. Call the `mutate` function with the appropriate payload to trigger the mutation. ```tsx import { useAddPet } from "../openapi/queries"; function App() { const { mutate } = useAddPet(); const handleAddPet = () => { mutate({ body: { name: "Fluffy" } }); }; return (

Add Pet

); } export default App; ``` -------------------------------- ### Run Codegen via npx Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/guides/introduction.mdx Execute the generator directly without adding it to project dependencies. ```bash $ npx --package @7nohe/openapi-react-query-codegen openapi-rq -i ./petstore.yaml ``` -------------------------------- ### Update Snapshots Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/contributing.md Updates snapshot files for testing, typically used after making changes that affect test outputs. ```bash pnpm snapshot ``` -------------------------------- ### Custom Query with TypeScript Client Source: https://context7.com/7nohe/openapi-react-query-codegen/llms.txt Utilize the generated TypeScript client for custom query configurations, including pre-API call logic and data transformations. Ensure to use the generated query key for cache consistency. ```tsx import { useQuery } from "@tanstack/react-query"; import { findPets } from "./openapi/requests/services.gen"; import { UseFindPetsKeyFn } from "./openapi/queries"; function CustomPetQuery() { const { data, error } = useQuery({ // Use the generated query key for cache consistency queryKey: UseFindPetsKeyFn({ query: { limit: 5 } }), queryFn: async () => { // Custom logic before the API call console.log("Fetching pets..."); const result = await findPets({ query: { limit: 5 } }); // Custom transformation return result.map((pet) => ({ ...pet, displayName: `${pet.name} (#${pet.id})`, })); }, // Custom query options staleTime: 5 * 60 * 1000, // 5 minutes retry: 3, refetchOnWindowFocus: false, }); if (error) return
Error: {error.message}
; return ( ); } ``` -------------------------------- ### Manage Cache with Generated Query Keys Source: https://context7.com/7nohe/openapi-react-query-codegen/llms.txt Use generated query key functions for precise cache invalidation and management. Ensure to import the necessary key functions and hook types. ```tsx import { useQueryClient } from "@tanstack/react-query"; import { useFindPets, useFindPetById, useDeletePet, UseFindPetsKeyFn, UseFindPetByIdKeyFn, } from "./openapi/queries"; function PetManager() { const queryClient = useQueryClient(); const { data: pets } = useFindPets({ query: { limit: 10 } }); const { data: selectedPet } = useFindPetById({ path: { id: 1 } }); const { mutate: deletePet } = useDeletePet({ onSuccess: (_, variables) => { // Invalidate the list query queryClient.invalidateQueries({ queryKey: UseFindPetsKeyFn({ query: { limit: 10 } }), }); // Remove the specific pet from cache queryClient.removeQueries({ queryKey: UseFindPetByIdKeyFn({ path: { id: variables.path.id } }), }); }, }); // Prefetch a specific pet on hover const handlePetHover = (petId: number) => { queryClient.prefetchQuery({ queryKey: UseFindPetByIdKeyFn({ path: { id: petId } }), queryFn: () => findPetById({ path: { id: petId } }), }); }; return ( ); } ``` -------------------------------- ### Use generated query hooks Source: https://context7.com/7nohe/openapi-react-query-codegen/llms.txt Implement the generated hooks in a component to fetch data with automatic caching and refetching capabilities. ```tsx import { useFindPets } from "./openapi/queries"; function PetList() { const { data, error, isLoading, refetch } = useFindPets({ query: { tags: ["dog", "cat"], limit: 10 }, }); if (isLoading) return
Loading...
; if (error) { return (

Failed to fetch pets: {error.message}

); } return ( ); } ``` -------------------------------- ### Invoke Generated Infinite Query Hook Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/guides/usage.mdx Import and use the generated hook to fetch paginated data in a React component. ```typescript import { useFindPaginatedPetsInfinite } from "@/openapi/queries/infiniteQueries"; const { data, fetchNextPage } = useFindPaginatedPetsInfinite({ query: { tags: [], limit: 10 } }); ``` -------------------------------- ### Implement useMutation with Cache Invalidation Source: https://context7.com/7nohe/openapi-react-query-codegen/llms.txt Use this hook to perform data mutations and trigger cache invalidation for related queries upon success. ```tsx import { useQueryClient } from "@tanstack/react-query"; import { useAddPet, useFindPets, UseFindPetsKeyFn } from "./openapi/queries"; function AddPetForm() { const queryClient = useQueryClient(); const [name, setName] = useState(""); const { mutate, isPending, isError, error } = useAddPet({ onSuccess: (newPet) => { // Invalidate the pets list cache to refetch with new data queryClient.invalidateQueries({ queryKey: UseFindPetsKeyFn({ query: { tags: [], limit: 10 } }), }); setName(""); console.log("Added pet:", newPet); }, onError: (error) => { console.error("Failed to add pet:", error.response?.data.message); }, }); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); mutate({ body: { name, tag: "new" }, }); }; return (
setName(e.target.value)} placeholder="Pet name" disabled={isPending} /> {isError &&

Error: {error.message}

}
); } ``` -------------------------------- ### Use Generated Hooks in Components Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/guides/introduction.mdx Import and utilize the generated hooks within your React components. ```tsx // src/App.tsx import { useFindPets } from "../openapi/queries"; function App() { const { data, error, refetch } = useFindPets(); if (error) return (

Failed to fetch pets

); return ( <>

Pet List

); } export default App; ``` -------------------------------- ### Invalidate Queries After Mutation Source: https://github.com/7nohe/openapi-react-query-codegen/blob/main/docs/src/content/docs/guides/usage.mdx Invalidate queries after a mutation to ensure the cache is updated. Use `queryClient.invalidateQueries` with the query key generated by the query hook's key function. ```tsx import { useFindPetsByStatus, useAddPet, UseFindPetsByStatusKeyFn, } from "../openapi/queries"; function App() { const [status, setStatus] = React.useState(["available"]); const { data } = useFindPetsByStatus({ query: { status } }); const { mutate } = useAddPet({ onSuccess: () => { queryClient.invalidateQueries({ // Call the query key function to get the query key // This is important to ensure the query key is created the same way as the query hook // This insures the cache is invalidated correctly and is typed correctly queryKey: [UseFindPetsByStatusKeyFn({ status })], }); }, }); return (

Pet List

); } export default App; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.