Skip to content

useQuery ​

The useQuery method allows you to use the original useQuery.

  • The result is the same as the original function.
  • The query key is [method, path, options], or [method, path] without options, so [method, path] matches every variant in invalidateQueries. options is the whole init object, such as { params: { path: { id: 1 } } }: pass that to setQueryData, not params.
  • data and error are fully typed.
  • A successful response without a body (a 204, an empty body, any HEAD response) gives data: null: TanStack Query does not accept undefined query data. useSuspenseQuery and queryOptions do the same, and the types say so: the data of an operation with a 204 is Body | null, and select gets null too. useInfiniteQuery pages and useMutation data stay undefined for such a response, as in openapi-react-query: TanStack Query accepts them, and their types include undefined.
  • You can pass query options as fourth parameter. Query options in the third parameter (the fetch options) are not read: useQuery("get", "/me", { retry: false }) sends a request and keeps the default retry. Write useQuery("get", "/me", undefined, { retry: false }).

TIP

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

Example ​

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

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

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

  return <div>{data.firstname}</div>;
};
ts
import createFetchClient from "openapi-typesafe-fetch";
import createClient from "openapi-typesafe-react-query";
import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typesafe

const fetchClient = createFetchClient<paths>({
  baseUrl: "https://myapi.dev/v1/",
});
export const $api = createClient(fetchClient);

Api ​

tsx
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 whole options object (params, headers, body and the rest) is part of the key. See Query Keys for more information.
  • queryOptions
  • queryClient

Released under the MIT License. Built on openapi-typescript, openapi-fetch and openapi-react-query.