Skip to content

OpenAPI React Query Codegen is a code generator for creating React Query (also known as TanStack Query) hooks based on your OpenAPI schema.

License

Notifications You must be signed in to change notification settings

7nohe/openapi-react-query-codegen

Repository files navigation

OpenAPI React Query Codegen

Node.js library that generates React Query (also called TanStack Query) hooks based on an OpenAPI specification file.

Features

  • Supports generation of custom react hooks that use React Query's useQuery and useMutation hooks
  • Supports the option to use pure TypeScript clients generated by OpenAPI Typescript Codegen

Install

$ npm install -D @7nohe/openapi-react-query-codegen

Usage

$ openapi-rq --help

  Usage: openapi-rq [options]

  Generate React Query code based on OpenAPI

  Options:
    -V, --version                 output the version number
    -p, --path <path>             Path to OpenAPI file
    -o, --output-dir [directory]  Directory to output the generated package (default: "openapi")
    -h, --help                    display help for command

Example Usage

Command

$ openapi-rq -p ./petstore.yaml

Output directory structure

- openapi
  - queries
    - index.ts <- custom react hooks
  - requests <- output code generated by OpenAPI Typescript Codegen

In your app

// App.tsx
import {
  usePetServiceFindPetsByStatus,
} from "../openapi/queries";
function App() {
  const { data } = usePetServiceFindPetsByStatus({ status: ["available"] });

  return (
    <div className="App">
      <h1>Pet List</h1>
      <ul>
        {data?.map((pet) => (
          <li key={pet.id}>{pet.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

You can also use pure TS clients.

import { useQuery } from "@tanstack/react-query";
import { PetService } from '../openapi/requests/services/PetService';
function App() {
  const { data } = useQuery(['MyKey'], () => {
    // Do something here
    
    return PetService.findPetsByStatus(['available']);
  });

  return (
    <div className="App">
      {/* .... */}
    </div>
  );
}

export default App;

License

MIT