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