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

QueryClient.md

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