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