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

QueryClient.md

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