openapi-react-query
Version:
Fast, type-safe @tanstack/react-query client to work with your OpenAPI schema.
66 lines (46 loc) • 2.01 kB
Markdown
is a type-safe tiny wrapper (1 kb) around [@tanstack/react-query](https://tanstack.com/query/latest/docs/framework/react/overview) to work with OpenAPI schema.
It works by using [openapi-fetch](../openapi-fetch) and [openapi-typescript](../openapi-typescript) so you get all the following features:
- ✅ No typos in URLs or params.
- ✅ All parameters, request bodies, and responses are type-checked and 100% match your schema
- ✅ No manual typing of your API
- ✅ Eliminates `any` types that hide bugs
- ✅ Eliminates `as` type overrides that can also hide bugs
## Setup
Install this library along with [openapi-fetch](../openapi-fetch) and [openapi-typescript](../openapi-typescript):
```bash
npm i openapi-react-query openapi-fetch
npm i -D openapi-typescript typescript
```
Next, generate TypeScript types from your OpenAPI schema using openapi-typescript:
```bash
npx openapi-typescript ./path/to/api/v1.yaml -o ./src/lib/api/v1.d.ts
```
## Usage
Once your types have been generated from your schema, you can create a [fetch client](../openapi-fetch), a react-query client and start querying your API.
```tsx
import createFetchClient from "openapi-fetch";
import createClient from "openapi-react-query";
import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript
const fetchClient = createFetchClient<paths>({
baseUrl: "https://myapi.dev/v1/",
});
const $api = createClient(fetchClient);
const MyComponent = () => {
const { data, error, isPending } = $api.useQuery(
"get",
"/blogposts/{post_id}",
{
params: {
path: { post_id: 5 },
},
}
);
if (isPending || !data) return "Loading...";
if (error) return `An error occurred: ${error.message}`;
return <div>{data.title}</div>;
};
```
> You can find more information about `createFetchClient` in the [openapi-fetch documentation](../openapi-fetch).
[ ](https://openapi-ts.dev/openapi-react-query/)
openapi-react-query