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