Generate swr hooks using OpenAPI schemas
swr-openapi is a type-safe wrapper around swr.
It works by using openapi-fetch and 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
anytypes that hide bugs - ✅ Also eliminates
astype overrides that can also hide bugs
import createClient from "openapi-fetch";
import { createQueryHook } from "swr-openapi";
import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript
const client = createClient<paths>({
baseUrl: "https://myapi.dev/v1/",
});
const useQuery = createQueryHook(client, "my-api");
function MyComponent() {
const { data, error, isLoading, isValidating, mutate } = useQuery(
"/blogposts/{post_id}",
{
params: {
path: { post_id: "123" },
},
},
);
if (isLoading || !data) return "Loading...";
if (error) return `An error occured: ${error.message}`;
return <div>{data.title}</div>;
}