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