fetchQuery(...)
The method allows you to execute a Queries without React Hooks with the full power of QueryClient.
To understand how fetchQuery
handles data and cache management,
refer to the TanStack queryClient.fetchQuery ๐ด documentation.
tip
fetchQuery
is particularly useful for server-side data fetching (SSR). When used on the server, it automatically
provides all the retry logic and caching capabilities inherent to TanStack Query.
This makes it an excellent choice for efficient and robust server-side data retrieval, ensuring your application benefits
from built-in error handling and performance optimizations.
const result = api.<service>.<operation>.fetchQuery(
{
parameters,
...fetchQueryOptions,
}
);
Argumentsโ
-
parameters: { path, query, header } | QueryKey | void
- Required, OpenAPI request parameters for the query, strictly-typed โจ
parameters
will be used to generate theQueryKey
- Optional, the base URL of the API
...fetchQueryOptions?: FetchQueryOptions
requestFn?: RequestFn
- Optional, a function that will be used to execute the request
baseUrl?: string
- Optional, represents the rest options of the fetchQuery(...) ๐ด method
queryOptions.queryFn
could be provided instead ofrequestFn
queryOptions.queryKey
could be provided instead ofparameters
Returnsโ
result: Promise<T>
- The result of the query execution
Examplesโ
- Basic
- With
queryFn
import { createAPIClient } from './api'; // generated by OpenAPI Qraft CLI
import { requestFn } from '@openapi-qraft/react';
import { QueryClient } from '@tanstack/react-query';
const api = createAPIClient({
requestFn,
queryClient: new QueryClient(),
baseUrl: 'https://api.sandbox.monite.com/v1',
});
/**
* Executes the request:
* ###
* GET /posts?limit=10
**/
const posts = await api.posts.getPosts.fetchQuery(
{ parameters: { query: { limit: 10 } } }
);
import { createAPIClient } from './api'; // generated by OpenAPI Qraft CLI
import { requestFn } from '@openapi-qraft/react';
import { QueryClient } from '@tanstack/react-query';
const api = createAPIClient({
requestFn,
queryClient: new QueryClient(),
baseUrl: 'https://api.sandbox.monite.com/v1',
});
/**
* Executes the request:
* ###
* GET /posts?limit=10
**/
const posts = await api.posts.getPosts.fetchQuery(
{
// โฌ๏ธ `queryKey` could be provided instead of `parameters`
queryKey: api.posts.getPosts.getQueryKey({ query: { limit: 10 } }),
// โฌ๏ธ `queryFn` could be provided
queryFn: function myCustomQueryFn({ queryKey, ...rest }) {
// ...
},
}
);