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({
87 queryKey,
88 queryFn,
89 staleTime: 10000,
90 })
91} catch (error) {
92 console.log(error)
93}
94```
95β
96**Options**
97β
98The options for `fetchQuery` are exactly the same as those of [`useQuery`](../../framework/react/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.
99β
100**Returns**
101β
102- `Promise<TData>`
103β
104## `queryClient.fetchInfiniteQuery`
105β
106`fetchInfiniteQuery` is similar to `fetchQuery` but can be used to fetch and cache an infinite query.
107β
108```tsx
109try {
110 const data = await queryClient.fetchInfiniteQuery({ queryKey, queryFn })
111 console.log(data.pages)
112} catch (error) {
113 console.log(error)
114}
115```
116β
117**Options**
118β
119The options for `fetchInfiniteQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
120β
121**Returns**
122β
123- `Promise<InfiniteData<TData, TPageParam>>`
124β
125## `queryClient.prefetchQuery`
126β
127`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.
128β
129```tsx
130await queryClient.prefetchQuery({ queryKey, queryFn })
131```
132β
133You can even use it with a default queryFn in your config!
134β
135```tsx
136await queryClient.prefetchQuery({ queryKey })
137```
138β
139**Options**
140β
141The options for `prefetchQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
142β
143**Returns**
144β
145- `Promise<void>`
146 - 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.
147β
148## `queryClient.prefetchInfiniteQuery`
149β
150`prefetchInfiniteQuery` is similar to `prefetchQuery` but can be used to prefetch and cache an infinite query.
151β
152```tsx
153await queryClient.prefetchInfiniteQuery({ queryKey, queryFn })
154```
155β
156**Options**
157β
158The options for `prefetchInfiniteQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
159β
160**Returns**
161β
162- `Promise<void>`
163 - 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.
164β
165## `queryClient.getQueryData`
166β
167`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.
168β
169```tsx
170const data = queryClient.getQueryData(queryKey)
171```
172β
173**Options**
174β
175- `queryKey: QueryKey`: [Query Keys](../../framework/react/guides/query-keys)
176β
177**Returns**
178β
179- `data: TQueryFnData | undefined`
180 - The data for the cached query, or `undefined` if the query does not exist.
181β
182## `queryClient.ensureQueryData`
183β
184`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.
185β
186```tsx
187const data = await queryClient.ensureQueryData({ queryKey, queryFn })
188```
189β
190**Options**
191β
192- the same options as [`fetchQuery`](#queryclientfetchquery)
193- `revalidateIfStale: boolean`
194 - Optional
195 - Defaults to `false`
196 - If set to `true`, stale data will be refetched in the background, but cached data will be returned immediately.
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 `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.
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- `queryKey: QueryKey`: [Query Keys](../../framework/react/guides/query-keys)
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- `options?: InvalidateOptions`:
322 - `throwOnError?: boolean`
323 - When set to `true`, this method will throw if any of the query refetch tasks fail.
324 - `cancelRefetch?: boolean`
325 - Defaults to `true`
326 - Per default, a currently running request will be cancelled before a new request is made
327 - When set to `false`, no refetch will be made if there is already a request running.
328β
329## `queryClient.refetchQueries`
330β
331The `refetchQueries` method can be used to refetch queries based on certain conditions.
332β
333Examples:
334β
335```tsx
336// refetch all queries:
337await queryClient.refetchQueries()
338β
339// refetch all stale queries:
340await queryClient.refetchQueries({ stale: true })
341β
342// refetch all active queries partially matching a query key:
343await queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' })
344β
345// refetch all active queries exactly matching a query key:
346await queryClient.refetchQueries({
347 queryKey: ['posts', 1],
348 type: 'active',
349 exact: true,
350})
351```
352β
353**Options**
354β
355- `filters?: QueryFilters`: [Query Filters](../../framework/react/guides/filters#query-filters)
356- `options?: RefetchOptions`:
357 - `throwOnError?: boolean`
358 - When set to `true`, this method will throw if any of the query refetch tasks fail.
359 - `cancelRefetch?: boolean`
360 - Defaults to `true`
361 - Per default, a currently running request will be cancelled before a new request is made
362 - When set to `false`, no refetch will be made if there is already a request running.
363β
364**Returns**
365β
366This 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`
367β
368## `queryClient.cancelQueries`
369β
370The `cancelQueries` method can be used to cancel outgoing queries based on their query keys or any other functionally accessible property/state of the query.
371β
372This 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.
373β
374```tsx
375await queryClient.cancelQueries({ queryKey: ['posts'], exact: true })
376```
377β
378**Options**
379β
380- `filters?: QueryFilters`: [Query Filters](../../framework/react/guides/filters#query-filters)
381β
382**Returns**
383β
384This method does not return anything
385β
386## `queryClient.removeQueries`
387β
388The `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.
389β
390```tsx
391queryClient.removeQueries({ queryKey, exact: true })
392```
393β
394**Options**
395β
396- `filters?: QueryFilters`: [Query Filters](../../framework/react/guides/filters#query-filters)
397β
398**Returns**
399β
400This method does not return anything
401β
402## `queryClient.resetQueries`
403β
404The `resetQueries` method can be used to reset queries in the cache to their
405initial state based on their query keys or any other functionally accessible
406property/state of the query.
407β
408This will notify subscribers — unlike `clear`, which removes all
409subscribers — and reset the query to its pre-loaded state — unlike
410`invalidateQueries`. If a query has `initialData`, the query's data will be
411reset to that. If a query is active, it will be refetched.
412β
413```tsx
414queryClient.resetQueries({ queryKey, exact: true })
415```
416β
417**Options**
418β
419- `filters?: QueryFilters`: [Query Filters](../../framework/react/guides/filters#query-filters)
420- `options?: ResetOptions`:
421 - `throwOnError?: boolean`
422 - When set to `true`, this method will throw if any of the query refetch tasks fail.
423 - `cancelRefetch?: boolean`
424 - Defaults to `true`
425 - Per default, a currently running request will be cancelled before a new request is made
426 - When set to `false`, no refetch will be made if there is already a request running.
427β
428**Returns**
429β
430This method returns a promise that resolves when all active queries have been refetched.
431β
432## `queryClient.isFetching`
433β
434This `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)
435β
436```tsx
437if (queryClient.isFetching()) {
438 console.log('At least one query is fetching!')
439}
440```
441β
442TanStack 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.
443β
444**Options**
445β
446- `filters?: QueryFilters`: [Query Filters](../../framework/react/guides/filters#query-filters)
447β
448**Returns**
449β
450This method returns the number of fetching queries.
451β
452## `queryClient.isMutating`
453β
454This `isMutating` method returns an `integer` representing how many mutations, if any, in the cache are currently fetching.
455β
456```tsx
457if (queryClient.isMutating()) {
458 console.log('At least one mutation is fetching!')
459}
460```
461β
462TanStack 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.
463β
464**Options**
465β
466- `filters: MutationFilters`: [Mutation Filters](../../framework/react/guides/filters#mutation-filters)
467β
468**Returns**
469β
470This method returns the number of fetching mutations.
471β
472## `queryClient.getDefaultOptions`
473β
474The `getDefaultOptions` method returns the default options which have been set when creating the client or with `setDefaultOptions`.
475β
476```tsx
477const defaultOptions = queryClient.getDefaultOptions()
478```
479β
480## `queryClient.setDefaultOptions`
481β
482The `setDefaultOptions` method can be used to dynamically set the default options for this queryClient. Previously defined default options will be overwritten.
483β
484```tsx
485queryClient.setDefaultOptions({
486 queries: {
487 staleTime: Infinity,
488 },
489})
490```
491β
492## `queryClient.getQueryDefaults`
493β
494The `getQueryDefaults` method returns the default options which have been set for specific queries:
495β
496```tsx
497const defaultOptions = queryClient.getQueryDefaults(['posts'])
498```
499β
500> Note that if several query defaults match the given query key, the **first** matching one is returned.
501> This could lead to unexpected behaviours. See [`setQueryDefaults`](#queryclientsetquerydefaults).
502β
503## `queryClient.setQueryDefaults`
504β
505`setQueryDefaults` can be used to set default options for specific queries:
506β
507```tsx
508queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts })
509β
510function Component() {
511 const { data } = useQuery({ queryKey: ['posts'] })
512}
513```
514β
515**Options**
516β
517- `queryKey: QueryKey`: [Query Keys](../../framework/react/guides/query-keys)
518- `options: QueryOptions`
519β
520> As stated in [`getQueryDefaults`](#queryclientgetquerydefaults), the order of registration of query defaults does matter.
521> 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.
522β
523## `queryClient.getMutationDefaults`
524β
525The `getMutationDefaults` method returns the default options which have been set for specific mutations:
526β
527```tsx
528const defaultOptions = queryClient.getMutationDefaults(['addPost'])
529```
530β
531## `queryClient.setMutationDefaults`
532β
533`setMutationDefaults` can be used to set default options for specific mutations:
534β
535```tsx
536queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost })
537β
538function Component() {
539 const { data } = useMutation({ mutationKey: ['addPost'] })
540}
541```
542β
543**Options**
544β
545- `mutationKey: unknown[]`
546- `options: MutationOptions`
547β
548> Similar to [`setQueryDefaults`](#queryclientsetquerydefaults), the order of registration does matter here.
549β
550## `queryClient.getQueryCache`
551β
552The `getQueryCache` method returns the query cache this client is connected to.
553β
554```tsx
555const queryCache = queryClient.getQueryCache()
556```
557β
558## `queryClient.getMutationCache`
559β
560The `getMutationCache` method returns the mutation cache this client is connected to.
561β
562```tsx
563const mutationCache = queryClient.getMutationCache()
564```
565β
566## `queryClient.clear`
567β
568The `clear` method clears all connected caches.
569β
570```tsx
571queryClient.clear()
572```
573β
574## `queryClient.resumePausedMutations`
575β
576Can be used to resume mutations that have been paused because there was no network connection.
577β
578```tsx
579queryClient.resumePausedMutations()
580```