| title | setQueryData |
|---|
The setQueryData method lets you directly update the cached data for a specific query (by method, path, and params) in a type-safe way, just like QueryClient.setQueryData.
- The updater function is fully type-safe and infers the correct data type from your OpenAPI schema.
- No manual type annotations are needed for the updater argument.
- Works with any query created by this client.
::: tip
You can find more information about setQueryData on the @tanstack/react-query documentation.
:::
::: code-group
import { $api } from './api'
export const App = () => {
// Update the cached list of posts.
const handleAddPost = (newPost) => {
$api.setQueryData(
'get',
'/posts',
(oldPosts = []) => [...oldPosts, newPost],
queryClient
)
}
// Update a single post by id.
const handleEditPost = (updatedPost) => {
$api.setQueryData(
'get',
'/posts/{post_id}',
(oldPost) => ({ ...oldPost, ...updatedPost }),
queryClient,
{ params: { path: { post_id: updatedPost.id } } }
)
}
return null
}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):::
If you try to update the cache with the wrong type, TypeScript will show an error:
$api.setQueryData(
'get',
'/posts',
// ❌ This updater returns a string, but the cached data should be an array of posts.
(oldPosts) => 'not an array', // TypeScript Error: Type 'string' is not assignable to type 'Post[]'.
queryClient
)$api.setQueryData(method, path, updater, queryClient, options?);Arguments
method(required)- The HTTP method for the query (e.g. "get").
path(required)- The path for the query (e.g. "/posts/{post_id}").
updater(required)- A function that receives the current cached data and returns the new data. The argument is fully type-inferred from your OpenAPI schema.
queryClient(required)- The QueryClient instance to update.
options- The fetch options (e.g. params) for the query. Only required if your endpoint requires parameters.
The updater function argument is fully type-inferred from your OpenAPI schema, so you get autocompletion and type safety for the cached data. No manual type annotations are needed.