Introduction
OpenAPI React Query Codegen is a code generator for creating React Query (also known as TanStack Query) hooks based on your OpenAPI schema.
Features
- Generates custom react hooks that use React Query’s
useQuery
,useSuspenseQuery
,useMutation
anduseInfiniteQuery
hooks - Generates custom functions that use React Query’s
ensureQueryData
andprefetchQuery
functions - Generates query keys and functions for query caching
- Generates pure TypeScript clients generated by @hey-api/openapi-ts
Installation
Register the command to the scripts
property in your package.json file.
You can also run the command without installing it in your project using the npx command.
Usage
For example, let’s generate React Query hooks for the Petstore API.
Then you will see the generated code in the openapi
directory.
Before using the generated hooks, you need to install the required dependencies.
Then, add the QueryClientProvider
to your application’s entry point.
Also, you can set the base URL and interceptors for the client generated by @hey-api/openapi-ts
.
In your React application, you can import the generated hooks and use them like this:
Output directory structure
Directoryopenapi
Directoryqueries
- index.ts Main file that exports common types, variables, and queries. Does not export suspense or prefetch hooks
- common.ts Common types
- ensureQueryData.ts Generated ensureQueryData functions
- queries.ts Generated query/mutation hooks
- infiniteQueries.ts Generated infinite query hooks
- suspenses.ts Generated suspense hooks
- prefetch.ts Generated prefetch functions
- requests Output code generated by
@hey-api/openapi-ts
To learn more about prefetchQuery
and ensureQueryData
functions, check out the following links: