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

QueryClient.md

616 lines22.0 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.md)
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```tsx
75try {
76 const data = await queryClient.fetchQuery({ queryKey, queryFn })
77} catch (error) {
78 console.log(error)
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)
94```
95​
96**Options**
97​
98The 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.
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)
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.md)
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.ensureInfiniteQueryData`
203​
204`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.
205​
206```tsx
207const data = await queryClient.ensureInfiniteQueryData({
208 queryKey,
209 queryFn,
210 initialPageParam,
211 getNextPageParam,
212})
213```
214​
215**Options**
216​
217- the same options as [`fetchInfiniteQuery`](#queryclientfetchinfinitequery)
218- `revalidateIfStale: boolean`
219 - Optional
220 - Defaults to `false`
221 - If set to `true`, stale data will be refetched in the background, but cached data will be returned immediately.
222​
223**Returns**
224​
225- `Promise<InfiniteData<TData, TPageParam>>`
226​
227## `queryClient.getQueriesData`
228​
229`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.
230​
231```tsx
232const data = queryClient.getQueriesData(filters)
233```
234​
235**Options**
236​
237- `filters: QueryFilters`: [Query Filters](../../framework/react/guides/filters.md#query-filters)
238 - if a filter is passed, the data with queryKeys matching the filter will be returned
239​
240**Returns**
241​
242- `[queryKey: QueryKey, data: TQueryFnData | undefined][]`
243 - 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.
244​
245**Caveats**
246​
247Because 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.
248​
249This distinction is more a "convenience" for ts devs that know which structure will be returned.
250​
251## `queryClient.setQueryData`
252​
253`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.
254​
255> 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.
256​
257```tsx
258queryClient.setQueryData(queryKey, updater)
259```
260​
261**Options**
262​
263- `queryKey: QueryKey`: [Query Keys](../../framework/react/guides/query-keys.md)
264- `updater: TQueryFnData | undefined | ((oldData: TQueryFnData | undefined) => TQueryFnData | undefined)`
265 - If non-function is passed, the data will be updated to this value
266 - If a function is passed, it will receive the old data value and be expected to return a new one.
267​
268**Using an updater value**
269​
270```tsx
271setQueryData(queryKey, newData)
272```
273​
274If the value is `undefined`, the query data is not updated.
275​
276**Using an updater function**
277​
278For convenience in syntax, you can also pass an updater function which receives the current data value and returns the new one:
279​
280```tsx
281setQueryData(queryKey, (oldData) => newData)
282```
283​
284If 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.
285​
286**Immutability**
287​
288Updates 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.
289​
290## `queryClient.getQueryState`
291​
292`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.
293​
294```tsx
295const state = queryClient.getQueryState(queryKey)
296console.log(state.dataUpdatedAt)
297```
298​
299**Options**
300​
301- `queryKey: QueryKey`: [Query Keys](../../framework/react/guides/query-keys.md)
302​
303## `queryClient.setQueriesData`
304​
305`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.
306​
307```tsx
308queryClient.setQueriesData(filters, updater)
309```
310​
311**Options**
312​
313- `filters: QueryFilters`: [Query Filters](../../framework/react/guides/filters.md#query-filters)
314 - if a filter is passed, queryKeys matching the filter will be updated
315- `updater: TQueryFnData | (oldData: TQueryFnData | undefined) => TQueryFnData`
316 - the [setQueryData](#queryclientsetquerydata) updater function or new data, will be called for each matching queryKey
317​
318## `queryClient.invalidateQueries`
319​
320The `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.
321​
322- If you **do not want active queries to refetch**, and simply be marked as invalid, you can use the `refetchType: 'none'` option.
323- If you **want inactive queries to refetch** as well, use the `refetchType: 'all'` option
324- For refetching, [queryClient.refetchQueries](#queryclientrefetchqueries) is called.
325​
326```tsx
327await queryClient.invalidateQueries(
328 {
329 queryKey: ['posts'],
330 exact,
331 refetchType: 'active',
332 },
333 { throwOnError, cancelRefetch },
335```
336​
337**Options**
338​
339- `filters?: QueryFilters`: [Query Filters](../../framework/react/guides/filters.md#query-filters)
340 - `queryKey?: QueryKey`: [Query Keys](../../framework/react/guides/query-keys.md)
341 - `refetchType?: 'active' | 'inactive' | 'all' | 'none'`
342 - Defaults to `'active'`
343 - 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.
344 - 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.
345 - When set to `all`, all queries that match the refetch predicate will be refetched in the background.
346 - When set to `none`, no queries will be refetched, and those that match the refetch predicate will be marked as invalid only.
347- `options?: InvalidateOptions`:
348 - `throwOnError?: boolean`
349 - When set to `true`, this method will throw if any of the query refetch tasks fail.
350 - `cancelRefetch?: boolean`
351 - Defaults to `true`
352 - Per default, a currently running request will be cancelled before a new request is made
353 - When set to `false`, no refetch will be made if there is already a request running.
354​
355## `queryClient.refetchQueries`
356​
357The `refetchQueries` method can be used to refetch queries based on certain conditions.
358​
359Examples:
360​
361```tsx
362// refetch all queries:
363await queryClient.refetchQueries()
364​
365// refetch all stale queries:
366await queryClient.refetchQueries({ stale: true })
367​
368// refetch all active queries partially matching a query key:
369await queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' })
370​
371// refetch all active queries exactly matching a query key:
372await queryClient.refetchQueries({
373 queryKey: ['posts', 1],
374 type: 'active',
375 exact: true,
376})
377```
378​
379**Options**
380​
381- `filters?: QueryFilters`: [Query Filters](../../framework/react/guides/filters.md#query-filters)
382- `options?: RefetchOptions`:
383 - `throwOnError?: boolean`
384 - When set to `true`, this method will throw if any of the query refetch tasks fail.
385 - `cancelRefetch?: boolean`
386 - Defaults to `true`
387 - Per default, a currently running request will be cancelled before a new request is made
388 - When set to `false`, no refetch will be made if there is already a request running.
389​
390**Returns**
391​
392This 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`
393​
394**Notes**
395​
396- Queries that are "disabled" because they only have disabled Observers will never be refetched.
397- Queries that are "static" because they only have Observers with a Static StaleTime will never be refetched.
398​
399## `queryClient.cancelQueries`
400​
401The `cancelQueries` method can be used to cancel outgoing queries based on their query keys or any other functionally accessible property/state of the query.
402​
403This 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.
404​
405```tsx
406await queryClient.cancelQueries(
407 { queryKey: ['posts'], exact: true },
408 { silent: true },
410```
411​
412**Options**
413​
414- `filters?: QueryFilters`: [Query Filters](../../framework/react/guides/filters.md#query-filters)
415- `cancelOptions?: CancelOptions`: [Cancel Options](../../framework/react/guides/query-cancellation.md#cancel-options)
416​
417**Returns**
418​
419This method does not return anything
420​
421## `queryClient.removeQueries`
422​
423The `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.
424​
425```tsx
426queryClient.removeQueries({ queryKey, exact: true })
427```
428​
429**Options**
430​
431- `filters?: QueryFilters`: [Query Filters](../../framework/react/guides/filters.md#query-filters)
432​
433**Returns**
434​
435This method does not return anything
436​
437## `queryClient.resetQueries`
438​
439The `resetQueries` method can be used to reset queries in the cache to their
440initial state based on their query keys or any other functionally accessible
441property/state of the query.
442​
443This will notify subscribers &mdash; unlike `clear`, which removes all
444subscribers &mdash; and reset the query to its pre-loaded state &mdash; unlike
445`invalidateQueries`. If a query has `initialData`, the query's data will be
446reset to that. If a query is active, it will be refetched.
447​
448```tsx
449queryClient.resetQueries({ queryKey, exact: true })
450```
451​
452**Options**
453​
454- `filters?: QueryFilters`: [Query Filters](../../framework/react/guides/filters.md#query-filters)
455- `options?: ResetOptions`:
456 - `throwOnError?: boolean`
457 - When set to `true`, this method will throw if any of the query refetch tasks fail.
458 - `cancelRefetch?: boolean`
459 - Defaults to `true`
460 - Per default, a currently running request will be cancelled before a new request is made
461 - When set to `false`, no refetch will be made if there is already a request running.
462​
463**Returns**
464​
465This method returns a promise that resolves when all active queries have been refetched.
466​
467## `queryClient.isFetching`
468​
469This `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)
470​
471```tsx
472if (queryClient.isFetching()) {
473 console.log('At least one query is fetching!')
475```
476​
477TanStack 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.
478​
479**Options**
480​
481- `filters?: QueryFilters`: [Query Filters](../../framework/react/guides/filters.md#query-filters)
482​
483**Returns**
484​
485This method returns the number of fetching queries.
486​
487## `queryClient.isMutating`
488​
489This `isMutating` method returns an `integer` representing how many mutations, if any, in the cache are currently fetching.
490​
491```tsx
492if (queryClient.isMutating()) {
493 console.log('At least one mutation is fetching!')
495```
496​
497TanStack 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.
498​
499**Options**
500​
501- `filters: MutationFilters`: [Mutation Filters](../../framework/react/guides/filters.md#mutation-filters)
502​
503**Returns**
504​
505This method returns the number of fetching mutations.
506​
507## `queryClient.getDefaultOptions`
508​
509The `getDefaultOptions` method returns the default options which have been set when creating the client or with `setDefaultOptions`.
510​
511```tsx
512const defaultOptions = queryClient.getDefaultOptions()
513```
514​
515## `queryClient.setDefaultOptions`
516​
517The `setDefaultOptions` method can be used to dynamically set the default options for this queryClient. Previously defined default options will be overwritten.
518​
519```tsx
520queryClient.setDefaultOptions({
521 queries: {
522 staleTime: Infinity,
523 },
524})
525```
526​
527## `queryClient.getQueryDefaults`
528​
529The `getQueryDefaults` method returns the default options which have been set for specific queries:
530​
531```tsx
532const defaultOptions = queryClient.getQueryDefaults(['posts'])
533```
534​
535> Note that if several query defaults match the given query key, they will be merged together based on the order of registration.
536> See [`setQueryDefaults`](#queryclientsetquerydefaults).
537​
538## `queryClient.setQueryDefaults`
539​
540`setQueryDefaults` can be used to set default options for specific queries:
541​
542```tsx
543queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts })
544​
545function Component() {
546 const { data } = useQuery({ queryKey: ['posts'] })
548```
549​
550**Options**
551​
552- `queryKey: QueryKey`: [Query Keys](../../framework/react/guides/query-keys.md)
553- `options: QueryOptions`
554​
555> As stated in [`getQueryDefaults`](#queryclientgetquerydefaults), the order of registration of query defaults does matter.
556> 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** .
557> This way, more specific defaults will override more generic defaults.
558​
559## `queryClient.getMutationDefaults`
560​
561The `getMutationDefaults` method returns the default options which have been set for specific mutations:
562​
563```tsx
564const defaultOptions = queryClient.getMutationDefaults(['addPost'])
565```
566​
567## `queryClient.setMutationDefaults`
568​
569`setMutationDefaults` can be used to set default options for specific mutations:
570​
571```tsx
572queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost })
573​
574function Component() {
575 const { data } = useMutation({ mutationKey: ['addPost'] })
577```
578​
579**Options**
580​
581- `mutationKey: unknown[]`
582- `options: MutationOptions`
583​
584> Similar to [`setQueryDefaults`](#queryclientsetquerydefaults), the order of registration does matter here.
585​
586## `queryClient.getQueryCache`
587​
588The `getQueryCache` method returns the query cache this client is connected to.
589​
590```tsx
591const queryCache = queryClient.getQueryCache()
592```
593​
594## `queryClient.getMutationCache`
595​
596The `getMutationCache` method returns the mutation cache this client is connected to.
597​
598```tsx
599const mutationCache = queryClient.getMutationCache()
600```
601​
602## `queryClient.clear`
603​
604The `clear` method clears all connected caches.
605​
606```tsx
607queryClient.clear()
608```
609​
610## `queryClient.resumePausedMutations`
611​
612Can be used to resume mutations that have been paused because there was no network connection.
613​
614```tsx
615queryClient.resumePausedMutations()
616```