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 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.
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.
197β
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**. To update multiple queries at once and match query keys partially, you need to use [`queryClient.setQueriesData`](#queryclientsetqueriesdata) instead.
207β
208After successful changing query's cached data via `setQueryData`, it will also trigger `onSuccess` callback from that query.
209β
210> 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.
211β
212```js
213queryClient.setQueryData(queryKey, updater)
214```
215β
216**Options**
217β
218- `queryKey: QueryKey`: [Query Keys](../guides/query-keys)
219- `updater: TData | (oldData: TData | undefined) => TData`
220 - If non-function is passed, the data will be updated to this value
221 - If a function is passed, it will receive the old data value and be expected to return a new one.
222β
223**Using an updater value**
224β
225```js
226setQueryData(queryKey, newData)
227```
228β
229**Using an updater function**
230β
231For convenience in syntax, you can also pass an updater function which receives the current data value and returns the new one:
232β
233```js
234setQueryData(queryKey, oldData => newData)
235```
236β
237## `queryClient.getQueryState`
238β
239`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.
240β
241```js
242const state = queryClient.getQueryState(queryKey)
243console.log(state.dataUpdatedAt)
244```
245β
246**Options**
247β
248- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
249- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
250β
251## `queryClient.setQueriesData`
252β
253`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.
254β
255```js
256queryClient.setQueriesData(queryKey | filters, updater)
257```
258β
259**Options**
260β
261- `queryKey: QueryKey`: [Query Keys](../guides/query-keys) | `filters: QueryFilters`: [Query Filters](../guides/filters#query-filters)
262 - if a queryKey is passed as first argument, queryKeys partially matching this param will be updated
263 - if a filter is passed, queryKeys matching the filter will be updated
264- `updater: TData | (oldData: TData | undefined) => TData`
265 - the [setQueryData](#queryclientsetquerydata) updater function or new data, will be called for each matching queryKey
266β
267## `queryClient.invalidateQueries`
268β
269The `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.
270β
271- If you **do not want active queries to refetch**, and simply be marked as invalid, you can use the `refetchActive: false` option.
272- If you **want inactive queries to refetch** as well, use the `refetchInactive: true` option
273β
274```js
275await queryClient.invalidateQueries('posts', {
276 exact,
277 refetchActive: true,
278 refetchInactive: false
279}, { throwOnError, cancelRefetch })
280```
281β
282**Options**
283β
284- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
285- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
286 - `refetchActive: Boolean`
287 - Defaults to `true`
288 - 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.
289 - `refetchInactive: Boolean`
290 - Defaults to `false`
291 - 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
292 - `refetchPage: (page: TData, index: number, allPages: TData[]) => boolean`
293 - Only for [Infinite Queries](../guides/infinite-queries#refetchpage)
294 - Use this function to specify which pages should be refetched
295- `options?: InvalidateOptions`:
296 - `throwOnError?: boolean`
297 - When set to `true`, this method will throw if any of the query refetch tasks fail.
298 - cancelRefetch?: boolean
299 - When set to `true`, then the current request will be cancelled before a new request is made
300β
301## `queryClient.refetchQueries`
302β
303The `refetchQueries` method can be used to refetch queries based on certain conditions.
304β
305Examples:
306β
307```js
308// refetch all queries:
309await queryClient.refetchQueries()
310β
311// refetch all stale queries:
312await queryClient.refetchQueries({ stale: true })
313β
314// refetch all active queries partially matching a query key:
315await queryClient.refetchQueries(['posts'], { active: true })
316β
317// refetch all active queries exactly matching a query key:
318await queryClient.refetchQueries(['posts', 1], { active: true, exact: true })
319```
320β
321**Options**
322β
323- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
324- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
325 - `refetchPage: (page: TData, index: number, allPages: TData[]) => boolean`
326 - Only for [Infinite Queries](../guides/infinite-queries#refetchpage)
327 - Use this function to specify which pages should be refetched
328- `options?: RefetchOptions`:
329 - `throwOnError?: boolean`
330 - When set to `true`, this method will throw if any of the query refetch tasks fail.
331 - cancelRefetch?: boolean
332 - When set to `true`, then the current request will be cancelled before a new request is made
333β
334**Returns**
335β
336This 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`
337β
338## `queryClient.cancelQueries`
339β
340The `cancelQueries` method can be used to cancel outgoing queries based on their query keys or any other functionally accessible property/state of the query.
341β
342This 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.
343β
344```js
345await queryClient.cancelQueries('posts', { exact: true })
346```
347β
348**Options**
349β
350- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
351- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
352β
353**Returns**
354β
355This method does not return anything
356β
357## `queryClient.removeQueries`
358β
359The `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.
360β
361```js
362queryClient.removeQueries(queryKey, { exact: true })
363```
364β
365**Options**
366β
367- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
368- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
369β
370**Returns**
371β
372This method does not return anything
373β
374## `queryClient.resetQueries`
375β
376The `resetQueries` method can be used to reset queries in the cache to their
377initial state based on their query keys or any other functionally accessible
378property/state of the query.
379β
380This will notify subscribers — unlike `clear`, which removes all
381subscribers — and reset the query to its pre-loaded state — unlike
382`invalidateQueries`. If a query has `initialData`, the query's data will be
383reset to that. If a query is active, it will be refetched.
384β
385```js
386queryClient.resetQueries(queryKey, { exact: true })
387```
388β
389**Options**
390β
391- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
392- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
393 - `refetchPage: (page: TData, index: number, allPages: TData[]) => boolean`
394 - Only for [Infinite Queries](../guides/infinite-queries#refetchpage)
395 - Use this function to specify which pages should be refetched
396- `options?: ResetOptions`:
397 - `throwOnError?: boolean`
398 - When set to `true`, this method will throw if any of the query refetch tasks fail.
399 - cancelRefetch?: boolean
400 - When set to `true`, then the current request will be cancelled before a new request is made
401β
402**Returns**
403β
404This method returns a promise that resolves when all active queries have been refetched.
405β
406## `queryClient.isFetching`
407β
408This `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)
409β
410```js
411if (queryClient.isFetching()) {
412 console.log('At least one query is fetching!')
413}
414```
415β
416React 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.
417β
418**Options**
419β
420- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
421- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
422β
423**Returns**
424β
425This method returns the number of fetching queries.
426β
427## `queryClient.isMutating`
428β
429This `isMutating` method returns an `integer` representing how many mutations, if any, in the cache are currently fetching.
430β
431```js
432if (queryClient.isMutating()) {
433 console.log('At least one mutation is fetching!')
434}
435```
436β
437React 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.
438β
439**Options**
440β
441- `filters: MutationFilters`: [Mutation Filters](../guides/filters#mutation-filters)
442β
443**Returns**
444β
445This method returns the number of fetching mutations.
446## `queryClient.getDefaultOptions`
447β
448The `getDefaultOptions` method returns the default options which have been set when creating the client or with `setDefaultOptions`.
449β
450```js
451const defaultOptions = queryClient.getDefaultOptions()
452```
453β
454## `queryClient.setDefaultOptions`
455β
456The `setDefaultOptions` method can be used to dynamically set the default options for this queryClient. Previously defined default options will be overwritten.
457β
458```js
459queryClient.setDefaultOptions({
460 queries: {
461 staleTime: Infinity,
462 },
463})
464```
465β
466## `queryClient.getQueryDefaults`
467β
468The `getQueryDefaults` method returns the default options which have been set for specific queries:
469β
470```js
471const defaultOptions = queryClient.getQueryDefaults('posts')
472```
473β
474## `queryClient.setQueryDefaults`
475β
476`setQueryDefaults` can be used to set default options for specific queries:
477β
478```js
479queryClient.setQueryDefaults('posts', { queryFn: fetchPosts })
480β
481function Component() {
482 const { data } = useQuery('posts')
483}
484```
485β
486**Options**
487β
488- `queryKey: QueryKey`: [Query Keys](../guides/query-keys)
489- `options: QueryOptions`
490β
491## `queryClient.getMutationDefaults`
492β
493The `getMutationDefaults` method returns the default options which have been set for specific mutations:
494β
495```js
496const defaultOptions = queryClient.getMutationDefaults('addPost')
497```
498β
499## `queryClient.setMutationDefaults`
500β
501`setMutationDefaults` can be used to set default options for specific mutations:
502β
503```js
504queryClient.setMutationDefaults('addPost', { mutationFn: addPost })
505β
506function Component() {
507 const { data } = useMutation('addPost')
508}
509```
510β
511**Options**
512β
513- `mutationKey: string | unknown[]`
514- `options: MutationOptions`
515β
516## `queryClient.getQueryCache`
517β
518The `getQueryCache` method returns the query cache this client is connected to.
519β
520```js
521const queryCache = queryClient.getQueryCache()
522```
523β
524## `queryClient.getMutationCache`
525β
526The `getMutationCache` method returns the mutation cache this client is connected to.
527β
528```js
529const mutationCache = queryClient.getMutationCache()
530```
531β
532## `queryClient.clear`
533β
534The `clear` method clears all connected caches.
535β
536```js
537queryClient.clear()
538```