
QueryClientThe QueryClient can be used to interact with a cache:
import { QueryClient, QueryCache } from 'react-query'const cache = new QueryCache()const client = new QueryClient({cache,defaultOptions: {queries: {staleTime: Infinity,},},})await client.prefetchQuery('posts', fetchPosts)
Its available methods are:
fetchQueryDataprefetchQuerygetQueryDatasetQueryDatagetQueryStatesetQueryDefaultsrefetchQueriesinvalidateQueriescancelQueriesremoveQuerieswatchQuerywatchQueriesisFetchinggetDefaultOptionssetDefaultOptionsOptions
cache: QueryCachedefaultOptions: DefaultOptionsclient.fetchQueryDatafetchQueryData 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
fetchQueryDataandsetQueryDatais thatfetchQueryDatais async and will ensure that duplicate requests for this query are not created withuseQueryinstances for the same query are rendered while the data is fetching.
try {const data = await client.fetchQueryData(queryKey, queryFn)} catch (error) {console.log(error)}
Specify a staleTime to only fetch when the data is older than a certain amount of time:
try {const data = await client.fetchQueryData(queryKey, queryFn, {staleTime: 10000,})} catch (error) {console.log(error)}
Options
The options for fetchQueryData are exactly the same as those of useQuery.
Returns
Promise<TData>client.prefetchQueryprefetchQuery 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 fetchQueryData except that is will not throw or return any data.
await client.prefetchQuery(queryKey, queryFn)
You can even use it with a default queryFn in your config!
await client.prefetchQuery(queryKey)
Options
The options for prefetchQuery are exactly the same as those of useQuery.
Returns
Promise<void>client.getQueryDatagetQueryData 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.
const data = client.getQueryData(queryKey)
Options
queryKey?: QueryKey: Query Keysfilters?: QueryFilters: Query FiltersReturns
data: TData | undefinedundefined if the query does not exist.client.setQueryDatasetQueryData 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 cacheTime of 5 minutes, the query will be garbage collected.
The difference between using
setQueryDataandfetchQueryDatais thatsetQueryDatais 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 usefetchQueryDatato handle the asynchronous fetch.
client.setQueryData(queryKey, updater)
Options
queryKey: QueryKey Query Keysupdater: unknown | (oldData: TData | undefined) => TDataUsing an updater value
setQueryData(queryKey, newData)
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:
setQueryData(queryKey, oldData => newData)
client.getQueryStategetQueryState 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.
const state = client.getQueryState(queryKey)console.log(state.updatedAt)
Options
queryKey?: QueryKey: Query Keysfilters?: QueryFilters: Query Filtersclient.setQueryDefaultssetQueryDefaults is a synchronous method to set default options for a specific query. If the query does not exist yet it will create it.
client.setQueryDefaults('posts', fetchPosts)function Component() {const { data } = useQuery('posts')}
Options
queryKey?: QueryKey: Query Keysfilters?: QueryFilters: Query Filtersclient.invalidateQueriesThe 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.
refetchActive: false option.refetchInactive: true optionawait client.invalidateQueries('posts', {exact,refetchActive = true,refetchInactive = false}, { throwOnError })
Options
queryKey?: QueryKey: Query Keysfilters?: QueryFilters: Query FiltersrefetchActive: Booleantruefalse, queries that match the refetch predicate and are actively being rendered via useQuery and friends will NOT be refetched in the background, and only marked as invalid.refetchInactive: Booleanfalsetrue, queries that match the refetch predicate and are not being rendered via useQuery and friends will be both marked as invalid and also refetched in the backgroundrefetchOptions?: RefetchOptions:throwOnError?: booleantrue, this method will throw if any of the query refetch tasks fail.client.refetchQueriesThe refetchQueries method can be used to refetch queries based on certain conditions.
Examples:
// refetch all queries:await client.refetchQueries()// refetch all stale queries:await client.refetchQueries({ stale: true })// refetch all active queries partially matching a query key:await client.refetchQueries(['posts'], { active: true })// refetch all active queries exactly matching a query key:await client.refetchQueries(['posts', 1], { active: true, exact: true })
Options
queryKey?: QueryKey: Query Keysfilters?: QueryFilters: Query FiltersrefetchOptions?: RefetchOptions:throwOnError?: booleantrue, this method will throw if any of the query refetch tasks fail.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
client.cancelQueriesThe 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.
await client.cancelQueries('posts', { exact: true })
Options
queryKey?: QueryKey: Query Keysfilters?: QueryFilters: Query FiltersReturns
This method does not return anything
client.removeQueriesThe 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.
client.removeQueries(queryKey, { exact: true })
Options
queryKey?: QueryKey: Query Keysfilters?: QueryFilters: Query FiltersReturns
This method does not return anything
client.watchQueryThe watchQuery method returns a QueryObserver instance which can be used to watch a query.
const observer = client.watchQuery('posts')const unsubscribe = observer.subscribe(result => {console.log(result)unsubscribe()})
Options
The options for watchQuery are exactly the same as those of useQuery.
Returns
QueryObserverclient.watchQueriesThe watchQueries method returns a QueriesObserver instance to watch multiple queries.
const observer = client.watchQueries([{ queryKey: ['post', 1], queryFn: fetchPost },{ queryKey: ['post', 2], queryFn: fetchPost },])const unsubscribe = observer.subscribe(result => {console.log(result)unsubscribe()})
Options
The options for watchQueries are exactly the same as those of useQueries.
Returns
QueriesObserverclient.isFetchingThis 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)
if (client.isFetching()) {console.log('At least one query is fetching!')}
React 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
queryKey?: QueryKey: Query Keysfilters?: QueryFilters: Query FiltersReturns
This method returns the number of fetching queries.
client.getDefaultOptionsThe getDefaultOptions method returns the default options which have been set when creating the client or with setDefaultOptions.
const defaultOptions = client.getDefaultOptions()
client.setDefaultOptionsThe setDefaultOptions method can be used to dynamically set the default options for this client.
client.setDefaultOptions({queries: {staleTime: Infinity,},})
The latest TanStack news, articles, and resources, sent to your inbox.