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 '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.getDefaultOptions`](#queryclientgetdefaultoptions)
43- [`queryClient.setDefaultOptions`](#queryclientsetdefaultoptions)
44- [`queryClient.getQueryDefaults`](#queryclientgetquerydefaults)
45- [`queryClient.setQueryDefaults`](#queryclientsetquerydefaults)
46- [`queryClient.getMutationDefaults`](#queryclientgetmutationdefaults)
47- [`queryClient.setMutationDefaults`](#queryclientsetmutationdefaults)
48- [`queryClient.getQueryCache`](#queryclientgetquerycache)
49- [`queryClient.getMutationCache`](#queryclientgetmutationcache)
50- [`queryClient.clear`](#queryclientclear)
51β
52**Options**
53β
54- `queryCache?: QueryCache`
55 - Optional
56 - The query cache this client is connected to.
57- `mutationCache?: MutationCache`
58 - Optional
59 - The mutation cache this client is connected to.
60- `defaultOptions?: DefaultOptions`
61 - Optional
62 - Define defaults for all queries and mutations using this queryClient.
63β
64## `queryClient.fetchQuery`
65β
66`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.
67β
68If 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.
69β
70> 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.
71β
72```js
73try {
74 const data = await queryClient.fetchQuery(queryKey, queryFn)
75} catch (error) {
76 console.log(error)
77}
78```
79β
80Specify a `staleTime` to only fetch when the data is older than a certain amount of time:
81β
82```js
83try {
84 const data = await queryClient.fetchQuery(queryKey, queryFn, {
85 staleTime: 10000,
86 })
87} catch (error) {
88 console.log(error)
89}
90```
91β
92**Options**
93β
94The options for `fetchQuery` are exactly the same as those of [`useQuery`](./useQuery), except the following: `enabled, refetchInterval, refetchIntervalInBackground, refetchOnWindowFocus, refetchOnReconnect, notifyOnChangeProps, notifyOnChangePropsExclusions, onSuccess, onError, onSettled, useErrorBoundary, select, suspense, keepPreviousData, placeholderData`; which are stictly 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.
95β
96**Returns**
97β
98- `Promise<TData>`
99β
100## `queryClient.fetchInfiniteQuery`
101β
102`fetchInfiniteQuery` is similar to `fetchQuery` but can be used to fetch and cache an infinite query.
103β
104```js
105try {
106 const data = await queryClient.fetchInfiniteQuery(queryKey, queryFn)
107 console.log(data.pages)
108} catch (error) {
109 console.log(error)
110}
111```
112β
113**Options**
114β
115The options for `fetchInfiniteQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
116β
117**Returns**
118β
119- `Promise<InfiniteData<TData>>`
120β
121## `queryClient.prefetchQuery`
122β
123`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.
124β
125```js
126await queryClient.prefetchQuery(queryKey, queryFn)
127```
128β
129You can even use it with a default queryFn in your config!
130β
131```js
132await queryClient.prefetchQuery(queryKey)
133```
134β
135**Options**
136β
137The options for `prefetchQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
138β
139**Returns**
140β
141- `Promise<void>`
142 - 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.
143β
144## `queryClient.prefetchInfiniteQuery`
145β
146`prefetchInfiniteQuery` is similar to `prefetchQuery` but can be used to prefetch and cache an infinite query.
147β
148```js
149await queryClient.prefetchInfiniteQuery(queryKey, queryFn)
150```
151β
152**Options**
153β
154The options for `prefetchInfiniteQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
155β
156**Returns**
157β
158- `Promise<void>`
159 - 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.
160β
161## `queryClient.getQueryData`
162β
163`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.
164β
165```js
166const data = queryClient.getQueryData(queryKey)
167```
168β
169**Options**
170β
171- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
172- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
173β
174**Returns**
175β
176- `data: TData | undefined`
177 - The data for the cached query, or `undefined` if the query does not exist.
178β
179## `queryClient.getQueriesData`
180β
181`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.
182β
183```js
184const data = queryClient.getQueriesData(queryKey | filters)
185```
186β
187**Options**
188β
189- `queryKey: QueryKey`: [Query Keys](../guides/query-keys) | `filters: QueryFilters`: [Query Filters](../guides/filters#query-filters)
190 - if a queryKey is passed as the argument, the data with queryKeys fuzzily matching this param will be returned
191 - if a filter is passed, the data with queryKeys matching the filter will be returned
192β
193**Returns**
194β
195- `[queryKey:QueryKey, data:TData | unknown][]`
196 - 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.
198**Caveats**
199β
200Because 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.
201β
202This distinction is more a "convenience" for ts devs that know which structure will be returned.
203β
204## `queryClient.setQueryData`
205β
206`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**.
207β
208> 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.
209β
210```js
211queryClient.setQueryData(queryKey, updater)
212```
213β
214**Options**
215β
216- `queryKey: QueryKey`: [Query Keys](../guides/query-keys)
217- `updater: TData | (oldData: TData | undefined) => TData`
218 - If non-function is passed, the data will be updated to this value
219 - If a function is passed, it will receive the old data value and be expected to return a new one.
220β
221**Using an updater value**
222β
223```js
224setQueryData(queryKey, newData)
225```
226β
227**Using an updater function**
228β
229For convenience in syntax, you can also pass an updater function which receives the current data value and returns the new one:
230β
231```js
232setQueryData(queryKey, oldData => newData)
233```
234β
235## `queryClient.getQueryState`
236β
237`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.
238β
239```js
240const state = queryClient.getQueryState(queryKey)
241console.log(state.dataUpdatedAt)
242```
243β
244**Options**
245β
246- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
247- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
248β
249## `queryClient.setQueriesData`
250β
251`setQueriesData` is a synchronous function that can be used to immediately update cached data of multiple queries. 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.
252β
253```js
254queryClient.setQueriesData(queryKey | filters, updater)
255```
256β
257**Options**
258β
259- `queryKey: QueryKey`: [Query Keys](../guides/query-keys) | `filters: QueryFilters`: [Query Filters](../guides/filters#query-filters)
260 - if a queryKey is passed as first argument, queryKeys fuzzily matching this param will be updated
261 - if a filter is passed, queryKeys matching the filter will be updated
262- `updater: TData | (oldData: TData | undefined) => TData`
263 - the [setQueryData](#queryclientsetquerydata) updater function or new data, will be called for each matching queryKey
264β
265## `queryClient.invalidateQueries`
266β
267The `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.
268β
269- If you **do not want active queries to refetch**, and simply be marked as invalid, you can use the `refetchActive: false` option.
270- If you **want inactive queries to refetch** as well, use the `refetchInactive: true` option
271β
272```js
273await queryClient.invalidateQueries('posts', {
274 exact,
275 refetchActive: true,
276 refetchInactive: false
277}, { throwOnError })
278```
279β
280**Options**
281β
282- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
283- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
284 - `refetchActive: Boolean`
285 - Defaults to `true`
286 - When set to `false`, queries that match the refetch predicate and are actively being rendered via `useQuery` and friends will NOT be refetched in the background, and only marked as invalid.
287 - `refetchInactive: Boolean`
288 - Defaults to `false`
289 - When set to `true`, queries that match the refetch predicate and are not being rendered via `useQuery` and friends will be both marked as invalid and also refetched in the background
290- `refetchOptions?: RefetchOptions`:
291 - `throwOnError?: boolean`
292 - When set to `true`, this method will throw if any of the query refetch tasks fail.
293β
294## `queryClient.refetchQueries`
295β
296The `refetchQueries` method can be used to refetch queries based on certain conditions.
297β
298Examples:
299β
300```js
301// refetch all queries:
302await queryClient.refetchQueries()
303β
304// refetch all stale queries:
305await queryClient.refetchQueries({ stale: true })
306β
307// refetch all active queries partially matching a query key:
308await queryClient.refetchQueries(['posts'], { active: true })
309β
310// refetch all active queries exactly matching a query key:
311await queryClient.refetchQueries(['posts', 1], { active: true, exact: true })
312```
313β
314**Options**
315β
316- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
317- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
318- `refetchOptions?: RefetchOptions`:
319 - `throwOnError?: boolean`
320 - When set to `true`, this method will throw if any of the query refetch tasks fail.
321β
322**Returns**
323β
324This 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`
325β
326## `queryClient.cancelQueries`
327β
328The `cancelQueries` method can be used to cancel outgoing queries based on their query keys or any other functionally accessible property/state of the query.
329β
330This 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.
331β
332```js
333await queryClient.cancelQueries('posts', { exact: true })
334```
335β
336**Options**
337β
338- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
339- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
340β
341**Returns**
342β
343This method does not return anything
344β
345## `queryClient.removeQueries`
346β
347The `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.
348β
349```js
350queryClient.removeQueries(queryKey, { exact: true })
351```
352β
353**Options**
354β
355- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
356- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
357β
358**Returns**
359β
360This method does not return anything
361β
362## `queryClient.resetQueries`
363β
364The `resetQueries` method can be used to reset queries in the cache to their
365initial state based on their query keys or any other functionally accessible
366property/state of the query.
367β
368This will notify subscribers — unlike `clear`, which removes all
369subscribers — and reset the query to its pre-loaded state — unlike
370`invalidateQueries`. If a query has `initialData`, the query's data will be
371reset to that. If a query is active, it will be refetched.
372β
373```js
374queryClient.resetQueries(queryKey, { exact: true })
375```
376β
377**Options**
378β
379- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
380- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
381- `resetOptions?: ResetOptions`:
382 - `throwOnError?: boolean`
383 - When set to `true`, this method will throw if any of the query refetch tasks fail.
384β
385**Returns**
386β
387This method returns a promise that resolves when all active queries have been refetched.
388β
389## `queryClient.isFetching`
390β
391This `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)
392β
393```js
394if (queryClient.isFetching()) {
395 console.log('At least one query is fetching!')
396}
397```
398β
399React 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.
400β
401**Options**
402β
403- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
404- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
405β
406**Returns**
407β
408This method returns the number of fetching queries.
409β
410## `queryClient.isMutating`
411β
412This `isMutating` method returns an `integer` representing how many mutations, if any, in the cache are currently fetching.
413β
414```js
415if (queryClient.isMutating()) {
416 console.log('At least one mutation is fetching!')
417}
418```
419β
420React 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.
421β
422**Options**
423β
424- `filters: MutationFilters`: [Mutation Filters](../guides/filters#mutation-filters)
425β
426**Returns**
427β
428This method returns the number of fetching mutations.
429## `queryClient.getDefaultOptions`
430β
431The `getDefaultOptions` method returns the default options which have been set when creating the client or with `setDefaultOptions`.
432β
433```js
434const defaultOptions = queryClient.getDefaultOptions()
435```
436β
437## `queryClient.setDefaultOptions`
438β
439The `setDefaultOptions` method can be used to dynamically set the default options for this queryClient. Previously defined default options will be overwritten.
440β
441```js
442queryClient.setDefaultOptions({
443 queries: {
444 staleTime: Infinity,
445 },
446})
447```
448β
449## `queryClient.getQueryDefaults`
450β
451The `getQueryDefaults` method returns the default options which have been set for specific queries:
452β
453```js
454const defaultOptions = queryClient.getQueryDefaults('posts')
455```
456β
457## `queryClient.setQueryDefaults`
458β
459`setQueryDefaults` can be used to set default options for specific queries:
460β
461```js
462queryClient.setQueryDefaults('posts', { queryFn: fetchPosts })
463β
464function Component() {
465 const { data } = useQuery('posts')
466}
467```
468β
469**Options**
470β
471- `queryKey: QueryKey`: [Query Keys](../guides/query-keys)
472- `options: QueryOptions`
473β
474## `queryClient.getMutationDefaults`
475β
476The `getMutationDefaults` method returns the default options which have been set for specific mutations:
477β
478```js
479const defaultOptions = queryClient.getMutationDefaults('addPost')
480```
481β
482## `queryClient.setMutationDefaults`
483β
484`setMutationDefaults` can be used to set default options for specific mutations:
485β
486```js
487queryClient.setMutationDefaults('addPost', { mutationFn: addPost })
488β
489function Component() {
490 const { data } = useMutation('addPost')
491}
492```
493β
494**Options**
495β
496- `mutationKey: string | unknown[]`
497- `options: MutationOptions`
498β
499## `queryClient.getQueryCache`
500β
501The `getQueryCache` method returns the query cache this client is connected to.
502β
503```js
504const queryCache = queryClient.getQueryCache()
505```
506β
507## `queryClient.getMutationCache`
508β
509The `getMutationCache` method returns the mutation cache this client is connected to.
510β
511```js
512const mutationCache = queryClient.getMutationCache()
513```
514β
515## `queryClient.clear`
516β
517The `clear` method clears all connected caches.
518β
519```js
520queryClient.clear()
521```