Skip to content

htunnicliff/swr-openapi

Repository files navigation

swr-openapi

Generate swr hooks using OpenAPI schemas

npm license

Introduction

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 any types that hide bugs
  • ✅ Also eliminates as type 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>;
}

📓 Docs

View Docs

About

Generate SWR hooks from OpenAPI schemas

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 9