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