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

QueryClient.md

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