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 ininvalidateQueries.optionsis the wholeinitobject, such as{ params: { path: { id: 1 } } }: pass that tosetQueryData, notparams. dataanderrorare fully typed.- A successful response without a body (a 204, an empty body, any HEAD response) gives
data: null: TanStack Query does not acceptundefinedquery data.useSuspenseQueryandqueryOptionsdo the same, and the types say so: the data of an operation with a 204 isBody | null, andselectgetsnulltoo.useInfiniteQuerypages anduseMutationdata stayundefinedfor such a response, as inopenapi-react-query: TanStack Query accepts them, and their types includeundefined. - 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 defaultretry. WriteuseQuery("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,bodyand the rest) is part of the key. See Query Keys for more information.
queryOptions- The original
useQueryoptions. - See more information
- The original
queryClient- The original
queryClientoption. - See more information
- The original