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