Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

QueryClient.md

624 lines22.7 KB

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