Generate swr
hooks using OpenAPI schemas
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
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!
},
},
},
);