QueryClient
#
The QueryClient
can be used to interact with a cache:
1import { QueryClient } from '@tanstack/react-query'
2
3const queryClient = new QueryClient({
4 defaultOptions: {
5 queries: {
6 staleTime: Infinity,
7 },
8 },
9})
10
11await queryClient.prefetchQuery({ queryKey: ['posts'], queryFn: fetchPosts })
Its available methods are:
queryClient.fetchQuery
queryClient.fetchInfiniteQuery
queryClient.prefetchQuery
queryClient.prefetchInfiniteQuery
queryClient.getQueryData
queryClient.ensureQueryData
queryClient.getQueriesData
queryClient.setQueryData
queryClient.getQueryState
queryClient.setQueriesData
queryClient.invalidateQueries
queryClient.refetchQueries
queryClient.cancelQueries
queryClient.removeQueries
queryClient.resetQueries
queryClient.isFetching
queryClient.isMutating
queryClient.getDefaultOptions
queryClient.setDefaultOptions
queryClient.getQueryDefaults
queryClient.setQueryDefaults
queryClient.getMutationDefaults
queryClient.setMutationDefaults
queryClient.getQueryCache
queryClient.getMutationCache
queryClient.clear
queryClient.resumePausedMutations
Options
queryCache?: QueryCache
- Optional
- The query cache this client is connected to.
mutationCache?: MutationCache
- Optional
- The mutation cache this client is connected to.
defaultOptions?: DefaultOptions
- Optional
- Define defaults for all queries and mutations using this queryClient.
- You can also define defaults to be used for hydration
queryClient.fetchQuery
#
fetchQuery
is an asynchronous method that can be used to fetch and cache a query. It will either resolve with the data or throw with the error. Use the prefetchQuery
method if you just want to fetch a query without needing the result.
If the query exists and the data is not invalidated or older than the given staleTime
, then the data from the cache will be returned. Otherwise it will try to fetch the latest data.
The difference between using
fetchQuery
andsetQueryData
is thatfetchQuery
is async and will ensure that duplicate requests for this query are not created withuseQuery
instances for the same query are rendered while the data is fetching.
1try {
2 const data = await queryClient.fetchQuery({ queryKey, queryFn })
3} catch (error) {
4 console.log(error)
5}
Specify a staleTime
to only fetch when the data is older than a certain amount of time:
1try {
2 const data = await queryClient.fetchQuery({
3 queryKey,
4 queryFn,
5 staleTime: 10000,
6 })
7} catch (error) {
8 console.log(error)
9}
Options
The options for fetchQuery
are exactly the same as those of useQuery
, except the following: enabled, refetchInterval, refetchIntervalInBackground, refetchOnWindowFocus, refetchOnReconnect, refetchOnMount, notifyOnChangeProps, throwOnError, select, suspense, placeholderData
; which are strictly for useQuery and useInfiniteQuery. You can check the source code for more clarity.
Returns
Promise<TData>
queryClient.fetchInfiniteQuery
#
fetchInfiniteQuery
is similar to fetchQuery
but can be used to fetch and cache an infinite query.
1try {
2 const data = await queryClient.fetchInfiniteQuery({ queryKey, queryFn })
3 console.log(data.pages)
4} catch (error) {
5 console.log(error)
6}
Options
The options for fetchInfiniteQuery
are exactly the same as those of fetchQuery
.
Returns
Promise<InfiniteData<TData, TPageParam>>
queryClient.prefetchQuery
#
prefetchQuery
is an asynchronous method that can be used to prefetch a query before it is needed or rendered with useQuery
and friends. The method works the same as fetchQuery
except that it will not throw or return any data.
1await queryClient.prefetchQuery({ queryKey, queryFn })
You can even use it with a default queryFn in your config!
1await queryClient.prefetchQuery({ queryKey })
Options
The options for prefetchQuery
are exactly the same as those of fetchQuery
.
Returns
Promise<void>
- A promise is returned that will either immediately resolve if no fetch is needed or after the query has been executed. It will not return any data or throw any errors.
queryClient.prefetchInfiniteQuery
#
prefetchInfiniteQuery
is similar to prefetchQuery
but can be used to prefetch and cache an infinite query.
1await queryClient.prefetchInfiniteQuery({ queryKey, queryFn })
Options
The options for prefetchInfiniteQuery
are exactly the same as those of fetchQuery
.
Returns
Promise<void>
- A promise is returned that will either immediately resolve if no fetch is needed or after the query has been executed. It will not return any data or throw any errors.
queryClient.getQueryData
#
getQueryData
is a synchronous function that can be used to get an existing query's cached data. If the query does not exist, undefined
will be returned.
1const data = queryClient.getQueryData(queryKey)
Options
queryKey: QueryKey
: Query Keys
Returns
data: TQueryFnData | undefined
- The data for the cached query, or
undefined
if the query does not exist.
- The data for the cached query, or
queryClient.ensureQueryData
#
ensureQueryData
is an asynchronous function that can be used to get an existing query's cached data. If the query does not exist, queryClient.fetchQuery
will be called and its results returned.
1const data = await queryClient.ensureQueryData({ queryKey, queryFn })
Options
- the same options as
fetchQuery
revalidateIfStale: boolean
- Optional
- Defaults to
false
- If set to
true
, stale data will be refetched in the background, but cached data will be returned immediately.
Returns
Promise<TData>
queryClient.getQueriesData
#
getQueriesData
is a synchronous function that can be used to get the cached data of multiple queries. Only queries that match the passed queryKey or queryFilter will be returned. If there are no matching queries, an empty array will be returned.
1const data = queryClient.getQueriesData(filters)
Options
filters: QueryFilters
: Query Filters- if a filter is passed, the data with queryKeys matching the filter will be returned
Returns
[queryKey: QueryKey, data: TQueryFnData | undefined][]
- An array of tuples for the matched query keys, or
[]
if there are no matches. The tuples are the query key and its associated data.
- An array of tuples for the matched query keys, or
Caveats
Because the returned data in each tuple can be of varying structures (i.e. using a filter to return "active" queries can return different data types), the TData
generic defaults to unknown
. If you provide a more specific type to TData
it is assumed that you are certain each tuple's data entry is all the same type.
This distinction is more a "convenience" for ts devs that know which structure will be returned.
queryClient.setQueryData
#
setQueryData
is a synchronous function that can be used to immediately update a query's cached data. If the query does not exist, it will be created. If the query is not utilized by a query hook in the default gcTime
of 5 minutes, the query will be garbage collected. To update multiple queries at once and match query keys partially, you need to use queryClient.setQueriesData
instead.
The difference between using
setQueryData
andfetchQuery
is thatsetQueryData
is sync and assumes that you already synchronously have the data available. If you need to fetch the data asynchronously, it's suggested that you either refetch the query key or usefetchQuery
to handle the asynchronous fetch.
1queryClient.setQueryData(queryKey, updater)
Options
queryKey: QueryKey
: Query Keysupdater: TQueryFnData | undefined | ((oldData: TQueryFnData | undefined) => TQueryFnData | undefined)
- If non-function is passed, the data will be updated to this value
- If a function is passed, it will receive the old data value and be expected to return a new one.
Using an updater value
1setQueryData(queryKey, newData)
If the value is undefined
, the query data is not updated.
Using an updater function
For convenience in syntax, you can also pass an updater function which receives the current data value and returns the new one:
1setQueryData(queryKey, (oldData) => newData)
If the updater function returns undefined
, the query data will not be updated. If the updater function receives undefined
as input, you can return undefined
to bail out of the update and thus not create a new cache entry.
Immutability
Updates via setQueryData
must be performed in an immutable way. DO NOT attempt to write directly to the cache by mutating oldData
or data that you retrieved via getQueryData
in place.
queryClient.getQueryState
#
getQueryState
is a synchronous function that can be used to get an existing query's state. If the query does not exist, undefined
will be returned.
1const state = queryClient.getQueryState(queryKey)
2console.log(state.dataUpdatedAt)
Options
queryKey: QueryKey
: Query Keys
queryClient.setQueriesData
#
setQueriesData
is a synchronous function that can be used to immediately update cached data of multiple queries by using filter function or partially matching the query key. Only queries that match the passed queryKey or queryFilter will be updated - no new cache entries will be created. Under the hood, setQueryData
is called for each existing query.
1queryClient.setQueriesData(filters, updater)
Options
filters: QueryFilters
: Query Filters- if a filter is passed, queryKeys matching the filter will be updated
updater: TQueryFnData | (oldData: TQueryFnData | undefined) => TQueryFnData
- the setQueryData updater function or new data, will be called for each matching queryKey
queryClient.invalidateQueries
#
The invalidateQueries
method can be used to invalidate and refetch single or multiple queries in the cache based on their query keys or any other functionally accessible property/state of the query. By default, all matching queries are immediately marked as invalid and active queries are refetched in the background.
- If you do not want active queries to refetch, and simply be marked as invalid, you can use the
refetchType: 'none'
option. - If you want inactive queries to refetch as well, use the
refetchType: 'all'
option
1await queryClient.invalidateQueries(
2 {
3 queryKey: ['posts'],
4 exact,
5 refetchType: 'active',
6 },
7 { throwOnError, cancelRefetch },
8)
Options
filters?: QueryFilters
: Query FiltersqueryKey?: QueryKey
: Query KeysrefetchType?: 'active' | 'inactive' | 'all' | 'none'
- Defaults to
'active'
- When set to
active
, only queries that match the refetch predicate and are actively being rendered viauseQuery
and friends will be refetched in the background. - When set to
inactive
, only queries that match the refetch predicate and are NOT actively being rendered viauseQuery
and friends will be refetched in the background. - When set to
all
, all queries that match the refetch predicate will be refetched in the background. - When set to
none
, no queries will be refetched, and those that match the refetch predicate will be marked as invalid only.
- Defaults to
options?: InvalidateOptions
:throwOnError?: boolean
- When set to
true
, this method will throw if any of the query refetch tasks fail.
- When set to
cancelRefetch?: boolean
- Defaults to
true
- Per default, a currently running request will be cancelled before a new request is made
- When set to
false
, no refetch will be made if there is already a request running.
- Defaults to
queryClient.refetchQueries
#
The refetchQueries
method can be used to refetch queries based on certain conditions.
Examples:
1// refetch all queries:
2await queryClient.refetchQueries()
3
4// refetch all stale queries:
5await queryClient.refetchQueries({ stale: true })
6
7// refetch all active queries partially matching a query key:
8await queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' })
9
10// refetch all active queries exactly matching a query key:
11await queryClient.refetchQueries({
12 queryKey: ['posts', 1],
13 type: 'active',
14 exact: true,
15})
Options
filters?: QueryFilters
: Query Filtersoptions?: RefetchOptions
:throwOnError?: boolean
- When set to
true
, this method will throw if any of the query refetch tasks fail.
- When set to
cancelRefetch?: boolean
- Defaults to
true
- Per default, a currently running request will be cancelled before a new request is made
- When set to
false
, no refetch will be made if there is already a request running.
- Defaults to
Returns
This function returns a promise that will resolve when all of the queries are done being refetched. By default, it will not throw an error if any of those queries refetches fail, but this can be configured by setting the throwOnError
option to true
queryClient.cancelQueries
#
The cancelQueries
method can be used to cancel outgoing queries based on their query keys or any other functionally accessible property/state of the query.
This is most useful when performing optimistic updates since you will likely need to cancel any outgoing query refetches so they don't clobber your optimistic update when they resolve.
1await queryClient.cancelQueries({ queryKey: ['posts'], exact: true })
Options
filters?: QueryFilters
: Query Filters
Returns
This method does not return anything
queryClient.removeQueries
#
The removeQueries
method can be used to remove queries from the cache based on their query keys or any other functionally accessible property/state of the query.
1queryClient.removeQueries({ queryKey, exact: true })
Options
filters?: QueryFilters
: Query Filters
Returns
This method does not return anything
queryClient.resetQueries
#
The resetQueries
method can be used to reset queries in the cache to their
initial state based on their query keys or any other functionally accessible
property/state of the query.
This will notify subscribers — unlike clear
, which removes all
subscribers — and reset the query to its pre-loaded state — unlike
invalidateQueries
. If a query has initialData
, the query's data will be
reset to that. If a query is active, it will be refetched.
1queryClient.resetQueries({ queryKey, exact: true })
Options
filters?: QueryFilters
: Query Filtersoptions?: ResetOptions
:throwOnError?: boolean
- When set to
true
, this method will throw if any of the query refetch tasks fail.
- When set to
cancelRefetch?: boolean
- Defaults to
true
- Per default, a currently running request will be cancelled before a new request is made
- When set to
false
, no refetch will be made if there is already a request running.
- Defaults to
Returns
This method returns a promise that resolves when all active queries have been refetched.
queryClient.isFetching
#
This isFetching
method returns an integer
representing how many queries, if any, in the cache are currently fetching (including background-fetching, loading new pages, or loading more infinite query results)
1if (queryClient.isFetching()) {
2 console.log('At least one query is fetching!')
3}
TanStack Query also exports a handy useIsFetching
hook that will let you subscribe to this state in your components without creating a manual subscription to the query cache.
Options
filters?: QueryFilters
: Query Filters
Returns
This method returns the number of fetching queries.
queryClient.isMutating
#
This isMutating
method returns an integer
representing how many mutations, if any, in the cache are currently fetching.
1if (queryClient.isMutating()) {
2 console.log('At least one mutation is fetching!')
3}
TanStack Query also exports a handy useIsMutating
hook that will let you subscribe to this state in your components without creating a manual subscription to the mutation cache.
Options
filters: MutationFilters
: Mutation Filters
Returns
This method returns the number of fetching mutations.
queryClient.getDefaultOptions
#
The getDefaultOptions
method returns the default options which have been set when creating the client or with setDefaultOptions
.
1const defaultOptions = queryClient.getDefaultOptions()
queryClient.setDefaultOptions
#
The setDefaultOptions
method can be used to dynamically set the default options for this queryClient. Previously defined default options will be overwritten.
1queryClient.setDefaultOptions({
2 queries: {
3 staleTime: Infinity,
4 },
5})
queryClient.getQueryDefaults
#
The getQueryDefaults
method returns the default options which have been set for specific queries:
1const defaultOptions = queryClient.getQueryDefaults(['posts'])
Note that if several query defaults match the given query key, the first matching one is returned. This could lead to unexpected behaviours. See
setQueryDefaults
.
queryClient.setQueryDefaults
#
setQueryDefaults
can be used to set default options for specific queries:
1queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts })
2
3function Component() {
4 const { data } = useQuery({ queryKey: ['posts'] })
5}
Options
queryKey: QueryKey
: Query Keysoptions: QueryOptions
As stated in
getQueryDefaults
, the order of registration of query defaults does matter. Since the first matching defaults are returned bygetQueryDefaults
, the registration should be made in the following order: from the least generic key to the most generic one. This way, in case of specific key, the first matching one would be the expected one.
queryClient.getMutationDefaults
#
The getMutationDefaults
method returns the default options which have been set for specific mutations:
1const defaultOptions = queryClient.getMutationDefaults(['addPost'])
queryClient.setMutationDefaults
#
setMutationDefaults
can be used to set default options for specific mutations:
1queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost })
2
3function Component() {
4 const { data } = useMutation({ mutationKey: ['addPost'] })
5}
Options
mutationKey: unknown[]
options: MutationOptions
Similar to
setQueryDefaults
, the order of registration does matter here.
queryClient.getQueryCache
#
The getQueryCache
method returns the query cache this client is connected to.
1const queryCache = queryClient.getQueryCache()
queryClient.getMutationCache
#
The getMutationCache
method returns the mutation cache this client is connected to.
1const mutationCache = queryClient.getMutationCache()
queryClient.clear
#
The clear
method clears all connected caches.
1queryClient.clear()
queryClient.resumePausedMutations
#
Can be used to resume mutations that have been paused because there was no network connection.
1queryClient.resumePausedMutations()