Skip to content

Files

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Latest commit

f3d2b0e · Jul 30, 2024

History

History

openapi-react-query

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Jun 23, 2024
Jul 1, 2024
Jul 1, 2024
Jul 30, 2024
Jun 23, 2024
Jun 24, 2024
Jun 23, 2024
Jun 23, 2024
Jul 30, 2024
Jun 23, 2024
Jun 24, 2024
Jun 23, 2024

openapi-react-query

openapi-react-query is a type-safe tiny wrapper (1 kb) around @tanstack/react-query to work with OpenAPI schema.

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

Setup

Install this library along with openapi-fetch and openapi-typescript:

npm i openapi-react-query openapi-fetch
npm i -D openapi-typescript typescript

Next, generate TypeScript types from your OpenAPI schema using openapi-typescript:

npx openapi-typescript ./path/to/api/v1.yaml -o ./src/lib/api/v1.d.ts

⚠️ Be sure to validate your schemas! openapi-typescript will err on invalid schemas.

Usage

Once your types has been generated from your schema, you can create a fetch client, a react-query client and start querying your API.

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, isLoading } = $api.useQuery(
    "get",
    "/blogposts/{post_id}",
    {
      params: {
        path: { post_id: 5 },
      },
    },
  );

  if (isLoading || !data) return "Loading...";

  if (error) return `An error occured: ${error.message}`;

  return <div>{data.title}</div>;
};

You can find more information about createFetchClient on the openapi-fetch documentation.

📓 Docs

View Docs