Open History to see the last commit
1---
2id: QueryClient
3title: QueryClient
4redirect_from:
5 - framework/react/reference/QueryClient
6---
7β
8The `QueryClient` can be used to interact with a cache:
9β
10```tsx
11import { QueryClient } from '@tanstack/react-query'
12β
13const queryClient = new QueryClient({
14 defaultOptions: {
15 queries: {
16 staleTime: Infinity,
17 },
18 },
19})
20β
21await queryClient.query({ queryKey: ['posts'], queryFn: fetchPosts })
22```
23β
24Its available methods are:
25β
26- [`queryClient.query`](#queryclient-query)
27- [`queryClient.infiniteQuery`](#queryclient-infinitequery)
28- [`queryClient.getQueryData`](#queryclient-getquerydata)
29- [`queryClient.getQueriesData`](#queryclient-getqueriesdata)
30- [`queryClient.setQueryData`](#queryclient-setquerydata)
31- [`queryClient.getQueryState`](#queryclient-getquerystate)
32- [`queryClient.setQueriesData`](#queryclient-setqueriesdata)
33- [`queryClient.invalidateQueries`](#queryclient-invalidatequeries)
34- [`queryClient.refetchQueries`](#queryclient-refetchqueries)
35- [`queryClient.cancelQueries`](#queryclient-cancelqueries)
36- [`queryClient.removeQueries`](#queryclient-removequeries)
37- [`queryClient.resetQueries`](#queryclient-resetqueries)
38- [`queryClient.isFetching`](#queryclient-isfetching)
39- [`queryClient.isMutating`](#queryclient-ismutating)
40- [`queryClient.getDefaultOptions`](#queryclient-getdefaultoptions)
41- [`queryClient.setDefaultOptions`](#queryclient-setdefaultoptions)
42- [`queryClient.getQueryDefaults`](#queryclient-getquerydefaults)
43- [`queryClient.setQueryDefaults`](#queryclient-setquerydefaults)
44- [`queryClient.getMutationDefaults`](#queryclient-getmutationdefaults)
45- [`queryClient.setMutationDefaults`](#queryclient-setmutationdefaults)
46- [`queryClient.getQueryCache`](#queryclient-getquerycache)
47- [`queryClient.getMutationCache`](#queryclient-getmutationcache)
48- [`queryClient.clear`](#queryclient-clear)
49- [`queryClient.resumePausedMutations`](#queryclient-resumepausedmutations)
50β
51**Options**
52β
53- `queryCache?: QueryCache`
54 - Optional
55 - The query cache this client is connected to.
56- `mutationCache?: MutationCache`
57 - Optional
58 - The mutation cache this client is connected to.
59- `defaultOptions?: DefaultOptions`
60 - Optional
61 - Define defaults for all queries and mutations using this queryClient.
62 - You can also define defaults to be used for [hydration](../framework/react/guides/ssr.md)
63β
64## `queryClient.query`
65β
66`query` is an asynchronous method that can be used to fetch and cache a query. It will either resolve with the data or throw with an error.
67β
68If 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.
69β
70```tsx
71try {
72 const data = await queryClient.query({ queryKey, queryFn })
73} catch (error) {
74 console.log(error)
75}
76```
77β
78Specify a `staleTime` to only fetch when the data is older than a certain amount of time:
79β
80```tsx
81try {
82 const data = await queryClient.query({
83 queryKey,
84 queryFn,
85 staleTime: 10000,
86 select: (data) => data.items,
87 })
88} catch (error) {
89 console.log(error)
90}
91```
92β
93**Options**
94β
95The options for `query` are exactly the same as those of [`useQuery`](../framework/react/reference/functions/useQuery.md), except the following: `enabled, refetchInterval, refetchIntervalInBackground, refetchOnWindowFocus, refetchOnReconnect, refetchOnMount, notifyOnChangeProps, throwOnError, suspense, placeholderData`; which are strictly for useQuery and useInfiniteQuery. You can check the [source code](https://github.com/TanStack/query/blob/7cd2d192e6da3df0b08e334ea1cf04cd70478827/packages/query-core/src/types.ts#L119) for more clarity.
96β
97**Returns**
98β
99- `Promise<TData>`
100β
101## `queryClient.infiniteQuery`
102β
103`infiniteQuery` is similar to `query` but can be used to fetch and cache an infinite query.
104β
105```tsx
106try {
107 const data = await queryClient.infiniteQuery({ queryKey, queryFn })
108 console.log(data.pages)
109} catch (error) {
110 console.log(error)
111}
112```
113β
114**Options**
115β
116The options for `infiniteQuery` are exactly the same as those of [`query`](#queryclient-query), with the addition of `initialPageParam`, `pages` and `getNextPageParam` options from [`useInfiniteQuery`](../framework/react/reference/functions/useInfiniteQuery.md).
117β
118**Returns**
119β
120- `Promise<InfiniteData<TData, TPageParam>>`
121β
122## `queryClient.getQueriesData`
123β
124`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.
125β
126```tsx
127const data = queryClient.getQueriesData(filters)
128```
129β
130**Options**
131β
132- `filters: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
133 - if a filter is passed, the data with queryKeys matching the filter will be returned
134β
135**Returns**
136β
137- `[queryKey: QueryKey, data: TQueryFnData | undefined][]`
138 - 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.
139β
140**Caveats**
141β
142Because 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.
143β
144This distinction is more a "convenience" for ts devs that know which structure will be returned.
145β
146## `queryClient.setQueryData`
147β
148`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 within the default `gcTime`, the query will be garbage collected. If the default `gcTime` has not been configured, it defaults to 5 minutes.** To update multiple queries at once and match query keys partially, you need to use [`queryClient.setQueriesData`](#queryclient-setqueriesdata) instead.
149β
150> The difference between using `setQueryData` and `query` is that `setQueryData` 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 use `query` to handle the asynchronous fetch.
151β
152```tsx
153queryClient.setQueryData(queryKey, updater)
154```
155β
156**Options**
157β
158- `queryKey: QueryKey`: [Query Keys](../framework/react/guides/query-keys.md)
159- `updater: TQueryFnData | undefined | ((oldData: TQueryFnData | undefined) => TQueryFnData | undefined)`
160 - If non-function is passed, the data will be updated to this value
161 - If a function is passed, it will receive the old data value and be expected to return a new one.
162β
163**Using an updater value**
164β
165```tsx
166setQueryData(queryKey, newData)
167```
168β
169If the value is `undefined`, the query data is not updated.
170β
171**Using an updater function**
172β
173For convenience in syntax, you can also pass an updater function which receives the current data value and returns the new one:
174β
175```tsx
176setQueryData(queryKey, (oldData) => newData)
177```
178β
179If 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.
180β
181**Immutability**
182β
183Updates 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.
184β
185## `queryClient.getQueryState`
186β
187`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.
188β
189```tsx
190const state = queryClient.getQueryState(queryKey)
191console.log(state.dataUpdatedAt)
192```
193β
194**Options**
195β
196- `queryKey: QueryKey`: [Query Keys](../framework/react/guides/query-keys.md)
197β
198## `queryClient.setQueriesData`
199β
200`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`](#queryclient-setquerydata) is called for each existing query.
201β
202```tsx
203queryClient.setQueriesData(filters, updater)
204```
205β
206**Options**
207β
208- `filters: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
209 - if a filter is passed, queryKeys matching the filter will be updated
210- `updater: TQueryFnData | (oldData: TQueryFnData | undefined) => TQueryFnData`
211 - the [setQueryData](#queryclient-setquerydata) updater function or new data, will be called for each matching queryKey
212β
213## `queryClient.invalidateQueries`
214β
215The `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.
216β
217- If you **do not want active queries to refetch**, and simply be marked as invalid, you can use the `refetchType: 'none'` option.
218- If you **want inactive queries to refetch** as well, use the `refetchType: 'all'` option
219- For refetching, [queryClient.refetchQueries](#queryclient-refetchqueries) is called.
220β
221```tsx
222await queryClient.invalidateQueries(
223 {
224 queryKey: ['posts'],
225 exact,
226 refetchType: 'active',
227 },
228 { throwOnError, cancelRefetch },
229)
230```
231β
232**Options**
233β
234- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
235 - `queryKey?: QueryKey`: [Query Keys](../framework/react/guides/query-keys.md)
236 - `refetchType?: 'active' | 'inactive' | 'all' | 'none'`
237 - Defaults to `'active'`
238 - When set to `active`, only queries that match the refetch predicate and are actively being rendered via `useQuery` and friends will be refetched in the background.
239 - When set to `inactive`, only queries that match the refetch predicate and are NOT actively being rendered via `useQuery` and friends will be refetched in the background.
240 - When set to `all`, all queries that match the refetch predicate will be refetched in the background.
241 - When set to `none`, no queries will be refetched, and those that match the refetch predicate will be marked as invalid only.
242- `options?: InvalidateOptions`:
243 - `throwOnError?: boolean`
244 - When set to `true`, this method will throw if any of the query refetch tasks fail.
245 - `cancelRefetch?: boolean`
246 - Defaults to `true`
247 - Per default, a currently running request will be cancelled before a new request is made
248 - When set to `false`, no refetch will be made if there is already a request running.
249β
250**Notes**
251β
252- Unlike [`refetchQueries`](#queryclient-refetchqueries), `invalidateQueries` marks matching queries as invalidated and then refetches `active` queries (unless otherwise specified with the `refetchType` option).
253- Unlike [`removeQueries`](#queryclient-removequeries), `invalidateQueries` keeps matching queries in the cache.
254β
255## `queryClient.refetchQueries`
256β
257The `refetchQueries` method can be used to refetch queries based on certain conditions.
258β
259Examples:
260β
261```tsx
262// refetch all queries:
263await queryClient.refetchQueries()
264β
265// refetch all stale queries:
266await queryClient.refetchQueries({ stale: true })
267β
268// refetch all active queries partially matching a query key:
269await queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' })
270β
271// refetch all active queries exactly matching a query key:
272await queryClient.refetchQueries({
273 queryKey: ['posts', 1],
274 type: 'active',
275 exact: true,
276})
277```
278β
279**Options**
280β
281- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
282- `options?: RefetchOptions`:
283 - `throwOnError?: boolean`
284 - When set to `true`, this method will throw if any of the query refetch tasks fail.
285 - `cancelRefetch?: boolean`
286 - Defaults to `true`
287 - Per default, a currently running request will be cancelled before a new request is made
288 - When set to `false`, no refetch will be made if there is already a request running.
289β
290**Returns**
291β
292This 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`
293β
294**Notes**
295β
296- Queries that are "disabled" because they only have disabled Observers will never be refetched.
297- Queries that are "static" because they only have Observers with a Static StaleTime will never be refetched.
298- Unlike [`invalidateQueries`](#queryclient-invalidatequeries), `refetchQueries` refetches all matching queries.
299β
300## `queryClient.cancelQueries`
301β
302The `cancelQueries` method can be used to cancel outgoing queries based on their query keys or any other functionally accessible property/state of the query.
303β
304This 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.
305β
306```tsx
307await queryClient.cancelQueries(
308 { queryKey: ['posts'], exact: true },
309 { silent: true },
310)
311```
312β
313**Options**
314β
315- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
316- `cancelOptions?: CancelOptions`: [Cancel Options](../framework/react/guides/query-cancellation.md#cancel-options)
317β
318**Returns**
319β
320This method does not return anything
321β
322## `queryClient.removeQueries`
323β
324The `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.
325β
326```tsx
327queryClient.removeQueries({ queryKey, exact: true })
328```
329β
330**Options**
331β
332- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
333β
334**Returns**
335β
336This method does not return anything
337β
338**Notes**
339β
340- Unlike [`invalidateQueries`](#queryclient-invalidatequeries) or [`refetchQueries`](#queryclient-refetchqueries), `removeQueries` removes matching queries from the cache instead of refetching them.
341β
342## `queryClient.resetQueries`
343β
344The `resetQueries` method can be used to reset queries in the cache to their
345initial state based on their query keys or any other functionally accessible
346property/state of the query.
347β
348This will notify subscribers — unlike `clear`, which removes all
349subscribers — and reset the query to its pre-loaded state — unlike
350`invalidateQueries`. If a query has `initialData`, the query's data will be
351reset to that. If a query is active, it will be refetched.
352β
353```tsx
354queryClient.resetQueries({ queryKey, exact: true })
355```
356β
357**Options**
358β
359- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
360- `options?: ResetOptions`:
361 - `throwOnError?: boolean`
362 - When set to `true`, this method will throw if any of the query refetch tasks fail.
363 - `cancelRefetch?: boolean`
364 - Defaults to `true`
365 - Per default, a currently running request will be cancelled before a new request is made
366 - When set to `false`, no refetch will be made if there is already a request running.
367β
368**Returns**
369β
370This method returns a promise that resolves when all active queries have been refetched.
371β
372## `queryClient.isFetching`
373β
374This `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)
375β
376```tsx
377if (queryClient.isFetching()) {
378 console.log('At least one query is fetching!')
379}
380```
381β
382TanStack Query also exports a handy [`useIsFetching`](../framework/react/reference/functions/useIsFetching.md) hook that will let you subscribe to this state in your components without creating a manual subscription to the query cache.
383β
384**Options**
385β
386- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
387β
388**Returns**
389β
390This method returns the number of fetching queries.
391β
392## `queryClient.isMutating`
393β
394This `isMutating` method returns an `integer` representing how many mutations, if any, in the cache are currently fetching.
395β
396```tsx
397if (queryClient.isMutating()) {
398 console.log('At least one mutation is fetching!')
399}
400```
401β
402TanStack Query also exports a handy [`useIsMutating`](../framework/react/reference/functions/useIsMutating.md) hook that will let you subscribe to this state in your components without creating a manual subscription to the mutation cache.
403β
404**Options**
405β
406- `filters: MutationFilters`: [Mutation Filters](../framework/react/guides/filters.md#mutation-filters)
407β
408**Returns**
409β
410This method returns the number of fetching mutations.
411β
412## `queryClient.getDefaultOptions`
413β
414The `getDefaultOptions` method returns the default options which have been set when creating the client or with `setDefaultOptions`.
415β
416```tsx
417const defaultOptions = queryClient.getDefaultOptions()
418```
419β
420## `queryClient.setDefaultOptions`
421β
422The `setDefaultOptions` method can be used to dynamically set the default options for this queryClient. Previously defined default options will be overwritten.
423β
424```tsx
425queryClient.setDefaultOptions({
426 queries: {
427 staleTime: Infinity,
428 },
429})
430```
431β
432## `queryClient.getQueryDefaults`
433β
434The `getQueryDefaults` method returns the default options which have been set for specific queries:
435β
436```tsx
437const defaultOptions = queryClient.getQueryDefaults(['posts'])
438```
439β
440> Note that if several query defaults match the given query key, they will be merged together based on the order of registration.
441> See [`setQueryDefaults`](#queryclient-setquerydefaults).
442β
443## `queryClient.setQueryDefaults`
444β
445`setQueryDefaults` can be used to set default options for specific queries:
446β
447```tsx
448queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts })
449β
450function Component() {
451 const { data } = useQuery({ queryKey: ['posts'] })
452}
453```
454β
455**Options**
456β
457- `queryKey: QueryKey`: [Query Keys](../framework/react/guides/query-keys.md)
458- `options: QueryOptions`
459β
460> As stated in [`getQueryDefaults`](#queryclient-getquerydefaults), the order of registration of query defaults does matter.
461> Since the matching defaults are merged by `getQueryDefaults`, the registration should be made in the following order: from the **most generic key** to the **least generic one** .
462> This way, more specific defaults will override more generic defaults.
463β
464## `queryClient.getMutationDefaults`
465β
466The `getMutationDefaults` method returns the default options which have been set for specific mutations:
467β
468```tsx
469const defaultOptions = queryClient.getMutationDefaults(['addPost'])
470```
471β
472## `queryClient.setMutationDefaults`
473β
474`setMutationDefaults` can be used to set default options for specific mutations:
475β
476```tsx
477queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost })
478β
479function Component() {
480 const { data } = useMutation({ mutationKey: ['addPost'] })
481}
482```
483β
484**Options**
485β
486- `mutationKey: unknown[]`
487- `options: MutationOptions`
488β
489> Similar to [`setQueryDefaults`](#queryclient-setquerydefaults), the order of registration does matter here.
490β
491## `queryClient.getQueryCache`
492β
493The `getQueryCache` method returns the query cache this client is connected to.
494β
495```tsx
496const queryCache = queryClient.getQueryCache()
497```
498β
499## `queryClient.getMutationCache`
500β
501The `getMutationCache` method returns the mutation cache this client is connected to.
502β
503```tsx
504const mutationCache = queryClient.getMutationCache()
505```
506β
507## `queryClient.clear`
508β
509The `clear` method clears all connected caches.
510β
511```tsx
512queryClient.clear()
513```
514β
515## `queryClient.resumePausedMutations`
516β
517Can be used to resume mutations that have been paused because there was no network connection.
518β
519```tsx
520queryClient.resumePausedMutations()
521```