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