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

QueryClient.md

521 lines17.9 KB

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)
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)
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)
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 &mdash; unlike `clear`, which removes all
369subscribers &mdash; and reset the query to its pre-loaded state &mdash; 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!')
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!')
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')
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')
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```