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

QueryClient.md

607 lines21.8 KB

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