swr-openapi
v5.1.0
Published
Generate SWR hooks from OpenAPI schemas
Downloads
5,012
Readme
Setup
npm install swr-openapi swr openapi-fetch
Follow openapi-typescript directions to generate TypeScript definitions for each service being used.
Here is an example of types being generated for a service via the command line:
npx openapi-typescript "https://sandwiches.example/openapi/json" --output ./types/sandwich-schema.ts
Basic Usage
Initialize an openapi-fetch client and create any desired hooks.
// sandwich-api.ts
import createClient from "openapi-fetch";
import { createQueryHook } from "swr-openapi";
import type { paths as SandwichPaths } from "./types/sandwich-schema";
const client = createClient<SandwichPaths>(/* ... */);
const useSandwiches = createQueryHook(client, "sandwich-api");
const { data, error, isLoading, isValidating, mutate } = useSandwiches(
"/sandwich/{id}", // <- Fully typed paths!
{
params: {
path: {
id: "123", // <- Fully typed params!
},
},
},
);