Skip to content

Instantly share code, notes, and snippets.

@radist2s
Last active April 14, 2025 22:07
Show Gist options
  • Save radist2s/c8834fd26e0a1c64a1cb7d377b29a5fe to your computer and use it in GitHub Desktop.
Save radist2s/c8834fd26e0a1c64a1cb7d377b29a5fe to your computer and use it in GitHub Desktop.
Combined openapi-react-query docs for RAG use
title
useQuery

{{ $frontmatter.title }}

The useQuery method allows you to use the original useQuery.

  • The result is the same as the original function.
  • The functionKey is [method, path, params].
  • data and error are fully typed.
  • You can pass queries options as fourth parameter.

::: tip You can find more information about useQuery on the @tanstack/react-query documentation. :::

Example

::: code-group

import { $api } from "./api";

export const App = () => {
  const { data, error, isLoading } = $api.useQuery("get", "/users/{user_id}", {
    params: {
      path: { user_id: 5 },
    },
  });

  if (!data || isLoading) return "Loading...";
  if (error) return `An error occured: ${error.message}`;

  return <div>{data.firstname}</div>;
};
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/",
});
export const $api = createClient(fetchClient);

:::

Api

const query = $api.useQuery(method, path, options, queryOptions, queryClient);

Arguments

  • method (required)
    • The HTTP method to use for the request.
    • The method is used as key. See Query Keys for more information.
  • path (required)
    • The pathname to use for the request.
    • Must be an available path for the given method in your schema.
    • The pathname is used as key. See Query Keys for more information.
  • options
    • The fetch options to use for the request.
    • Only required if the OpenApi schema requires parameters.
    • The options params are used as key. See Query Keys for more information.
  • queryOptions
  • queryClient


title: useMutation

{{ $frontmatter.title }}

The useMutation method allows you to use the original useMutation.

  • The result is the same as the original function.
  • The mutationKey is [method, path].
  • data and error are fully typed.

::: tip You can find more information about useMutation on the @tanstack/react-query documentation. :::

Example

::: code-group

import { $api } from "./api";

export const App = () => {
  const { mutate } = $api.useMutation("patch", "/users");

  return (
    <button onClick={() => mutate({ body: { firstname: "John" } })}>
      Update
    </button>
  );
};
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/",
});
export const $api = createClient(fetchClient);

:::

Api

const query = $api.useMutation(method, path, queryOptions, queryClient);

Arguments

  • method (required)
    • The HTTP method to use for the request.
    • The method is used as key. See Query Keys for more information.
  • path (required)
    • The pathname to use for the request.
    • Must be an available path for the given method in your schema.
    • The pathname is used as key. See Query Keys for more information.
  • queryOptions
  • queryClient


title: useInfiniteQuery

{{ $frontmatter.title }}

The useInfiniteQuery method allows you to use the original useInfiniteQuery

  • The result is the same as the original function.
  • The queryKey is [method, path, params].
  • data and error are fully typed.
  • You can pass infinite query options as fourth parameter.

::: tip You can find more information about useInfiniteQuery on the @tanstack/react-query documentation. :::

Example

::: code-group

import { $api } from "./api";
const PostList = () => {
  const { data, fetchNextPage, hasNextPage, isFetching } =
    $api.useInfiniteQuery(
      "get",
      "/posts",
      {
        params: {
          query: {
            limit: 10,
          },
        },
      },
      {
        getNextPageParam: (lastPage) => lastPage.nextPage,
        initialPageParam: 0,
      }
    );

  return (
    <div>
      {data?.pages.map((page, i) => (
        <div key={i}>
          {page.items.map((post) => (
            <div key={post.id}>{post.title}</div>
          ))}
        </div>
      ))}
      {hasNextPage && (
        <button onClick={() => fetchNextPage()} disabled={isFetching}>
          {isFetching ? "Loading..." : "Load More"}
        </button>
      )}
    </div>
  );
};

export const App = () => {
  return (
    <ErrorBoundary fallbackRender={({ error }) => `Error: ${error.message}`}>
      <MyComponent />
    </ErrorBoundary>
  );
};
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/",
});
export const $api = createClient(fetchClient);

:::

Api

const query = $api.useInfiniteQuery(
  method,
  path,
  options,
  infiniteQueryOptions,
  queryClient
);

Arguments

  • method (required)
    • The HTTP method to use for the request.
    • The method is used as key. See Query Keys for more information.
  • path (required)
    • The pathname to use for the request.
    • Must be an available path for the given method in your schema.
    • The pathname is used as key. See Query Keys for more information.
  • options
    • The fetch options to use for the request.
    • Only required if the OpenApi schema requires parameters.
    • The options params are used as key. See Query Keys for more information.
  • infiniteQueryOptions
  • queryClient


title: useSuspenseQuery

{{ $frontmatter.title }}

The useSuspenseQuery method allows you to use the original useSuspenseQuery.

  • The result is the same as the original function.
  • The functionKey is [method, path, params].
  • data and error are fully typed.
  • You can pass queries options as fourth parameter.

::: tip You can find more information about useSuspenseQuery on the @tanstack/react-query documentation. :::

Example

::: code-group

import { ErrorBoundary } from "react-error-boundary";
import { $api } from "./api";

const MyComponent = () => {
  const { data } = $api.useSuspenseQuery("get", "/users/{user_id}", {
    params: {
      path: { user_id: 5 },
    },
  });

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

export const App = () => {
  return (
    <ErrorBoundary fallbackRender={({ error }) => `Error: ${error.message}`}>
      <MyComponent />
    </ErrorBoundary>
  );
};
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/",
});
export const $api = createClient(fetchClient);

:::

Api

const query = $api.useSuspenseQuery(method, path, options, queryOptions, queryClient);

Arguments

  • method (required)
    • The HTTP method to use for the request.
    • The method is used as key. See Query Keys for more information.
  • path (required)
    • The pathname to use for the request.
    • Must be an available path for the given method in your schema.
    • The pathname is used as key. See Query Keys for more information.
  • options
    • The fetch options to use for the request.
    • Only required if the OpenApi schema requires parameters.
    • The options params are used as key. See Query Keys for more information.
  • queryOptions
  • queryClient


title: queryOptions

{{ $frontmatter.title }}

The queryOptions method allows you to construct type-safe Query Options.

queryOptions can be used together with @tanstack/react-query APIs that take query options, such as useQuery, useQueries, usePrefetchQuery and QueryClient.fetchQuery among many others.

If you would like to use a query API that is not explicitly supported by openapi-react-query, this is the way to go.

Examples

useQuery example rewritten using queryOptions.

::: code-group

import { useQuery } from '@tanstack/react-query';
import { $api } from "./api";

export const App = () => {
  const { data, error, isLoading } = useQuery(
    $api.queryOptions("get", "/users/{user_id}", {
      params: {
        path: { user_id: 5 },
      },
    }),
  );

  if (!data || isLoading) return "Loading...";
  if (error) return `An error occured: ${error.message}`;

  return <div>{data.firstname}</div>;
};
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/",
});
export const $api = createClient(fetchClient);

:::

::: info Good to Know

Both useQuery and useSuspenseQuery use queryOptions under the hood.

:::

Usage with useQueries.

::: code-group

import { useQueries } from '@tanstack/react-query';
import { $api } from "./api";

export const useUsersById = (userIds: number[]) => (
  useQueries({
    queries: userIds.map((userId) => (
      $api.queryOptions("get", "/users/{user_id}", {
        params: {
          path: { user_id: userId },
        },
      })
    ))
  })
);
import createFetchClient from "openapi-fetch";
import createClient from "openapi-
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment