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```tsx
11import { QueryClient } from '@tanstack/react-query'
12β
13const queryClient = new QueryClient({
14 defaultOptions: {
15 queries: {
16 staleTime: Infinity,
17 },
18 },
19})
20β
21await queryClient.prefetchQuery({ queryKey: ['posts'], queryFn: 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.ensureQueryData`](#queryclientensurequerydata)
32- [`queryClient.getQueriesData`](#queryclientgetqueriesdata)
33- [`queryClient.setQueryData`](#queryclientsetquerydata)
34- [`queryClient.getQueryState`](#queryclientgetquerystate)
35- [`queryClient.setQueriesData`](#queryclientsetqueriesdata)
36- [`queryClient.invalidateQueries`](#queryclientinvalidatequeries)
37- [`queryClient.refetchQueries`](#queryclientrefetchqueries)
38- [`queryClient.cancelQueries`](#queryclientcancelqueries)
39- [`queryClient.removeQueries`](#queryclientremovequeries)
40- [`queryClient.resetQueries`](#queryclientresetqueries)
41- [`queryClient.isFetching`](#queryclientisfetching)
42- [`queryClient.isMutating`](#queryclientismutating)
43- [`queryClient.getLogger`](#queryclientgetlogger)
44- [`queryClient.getDefaultOptions`](#queryclientgetdefaultoptions)
45- [`queryClient.setDefaultOptions`](#queryclientsetdefaultoptions)
46- [`queryClient.getQueryDefaults`](#queryclientgetquerydefaults)
47- [`queryClient.setQueryDefaults`](#queryclientsetquerydefaults)
48- [`queryClient.getMutationDefaults`](#queryclientgetmutationdefaults)
49- [`queryClient.setMutationDefaults`](#queryclientsetmutationdefaults)
50- [`queryClient.getQueryCache`](#queryclientgetquerycache)
51- [`queryClient.getMutationCache`](#queryclientgetmutationcache)
52- [`queryClient.clear`](#queryclientclear)
53- [`queryClient.resumePausedMutations`](#queryclientresumepausedmutations)
54β
55**Options**
56β
57- `queryCache?: QueryCache`
58 - Optional
59 - The query cache this client is connected to.
60- `mutationCache?: MutationCache`
61 - Optional
62 - The mutation cache this client is connected to.
63- `logger?: Logger`
64 - Optional
65 - The logger this client uses to log debugging information, warnings and errors. If not set, `console` is the default logger.
66- `defaultOptions?: DefaultOptions`
67 - Optional
68 - Define defaults for all queries and mutations using this queryClient.
69β
70## `queryClient.fetchQuery`
71β
72`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.
73β
74If 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.
75β
76> 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.
77β
78```tsx
79try {
80 const data = await queryClient.fetchQuery({ queryKey, queryFn })
81} catch (error) {
82 console.log(error)
83}
84```
85β
86Specify a `staleTime` to only fetch when the data is older than a certain amount of time:
87β
88```tsx
89try {
90 const data = await queryClient.fetchQuery({ queryKey, queryFn, staleTime: 10000 })
91} catch (error) {
92 console.log(error)
93}
94```
95β
96**Options**
97β
98The options for `fetchQuery` are exactly the same as those of [`useQuery`](../reference/useQuery), except the following: `enabled, refetchInterval, refetchIntervalInBackground, refetchOnWindowFocus, refetchOnReconnect, notifyOnChangeProps, 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.
99β
100**Returns**
101β
102- `Promise<TData>`
103β
104## `queryClient.fetchInfiniteQuery`
105β
106`fetchInfiniteQuery` is similar to `fetchQuery` but can be used to fetch and cache an infinite query.
107β
108```tsx
109try {
110 const data = await queryClient.fetchInfiniteQuery({ queryKey, queryFn })
111 console.log(data.pages)
112} catch (error) {
113 console.log(error)
114}
115```
116β
117**Options**
118β
119The options for `fetchInfiniteQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
120β
121**Returns**
122β
123- `Promise<InfiniteData<TData>>`
124β
125## `queryClient.prefetchQuery`
126β
127`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.
128β
129```tsx
130await queryClient.prefetchQuery({ queryKey, queryFn })
131```
132β
133You can even use it with a default queryFn in your config!
134β
135```tsx
136await queryClient.prefetchQuery({ queryKey })
137```
138β
139**Options**
140β
141The options for `prefetchQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
142β
143**Returns**
144β
145- `Promise<void>`
146 - 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.
147β
148## `queryClient.prefetchInfiniteQuery`
149β
150`prefetchInfiniteQuery` is similar to `prefetchQuery` but can be used to prefetch and cache an infinite query.
151β
152```tsx
153await queryClient.prefetchInfiniteQuery({ queryKey, queryFn })
154```
155β
156**Options**
157β
158The options for `prefetchInfiniteQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
159β
160**Returns**
161β
162- `Promise<void>`
163 - 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.
164β
165## `queryClient.getQueryData`
166β
167`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.
168β
169```tsx
170const data = queryClient.getQueryData(queryKey)
171```
172β
173**Options**
174β
175- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
176β
177**Returns**
178β
179- `data: TQueryFnData | undefined`
180 - The data for the cached query, or `undefined` if the query does not exist.
181β
182## `queryClient.ensureQueryData`
183β
184`ensureQueryData` is an asynchronous function that can be used to get an existing query's cached data. If the query does not exist, `queryClient.fetchQuery` will be called and its results returned.
185β
186```tsx
187const data = await queryClient.ensureQueryData({ queryKey, queryFn })
188```
189β
190**Options**
191β
192- The options for `ensureQueryData` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery) except that `queryKey` is required.
193β
194**Returns**
195β
196- `Promise<TData>`
197β
198## `queryClient.getQueriesData`
199β
200`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.
201β
202```tsx
203const data = queryClient.getQueriesData(filters)
204```
205β
206**Options**
207β
208- `filters: QueryFilters`: [Query Filters](../guides/filters#query-filters)
209 - if a filter is passed, the data with queryKeys matching the filter will be returned
210β
211**Returns**
212β
213- `[queryKey: QueryKey, data: TQueryFnData | undefined][]`
214 - 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.
215β
216**Caveats**
217β
218Because 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.
219β
220This distinction is more a "convenience" for ts devs that know which structure will be returned.
221β
222## `queryClient.setQueryData`
223β
224`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.
225β
226> 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.
227β
228```tsx
229queryClient.setQueryData(queryKey, updater)
230```
231β
232**Options**
233β
234- `queryKey: QueryKey`: [Query Keys](../guides/query-keys)
235- `updater: TQueryFnData | undefined | ((oldData: TQueryFnData | undefined) => TQueryFnData | undefined)`
236 - If non-function is passed, the data will be updated to this value
237 - If a function is passed, it will receive the old data value and be expected to return a new one.
238β
239**Using an updater value**
240β
241```tsx
242setQueryData(queryKey, newData)
243```
244β
245If the value is `undefined`, the query data is not updated.
246β
247**Using an updater function**
248β
249For convenience in syntax, you can also pass an updater function which receives the current data value and returns the new one:
250β
251```tsx
252setQueryData(queryKey, oldData => newData)
253```
254β
255If the updater function returns `undefined`, the query data will not be updated. If the updater function receives `undefined` as input, you can return `undefined` to bail out of the update and thus _not_ create a new cache entry.
256β
257**Immutability**
258β
259Updates via `setQueryData` must be performed in an _immuatable_ way. **DO NOT** attempt to write directly to the cache by mutating `oldData` or data that you retrieved via `getQueryData` in place.
260β
261## `queryClient.getQueryState`
262β
263`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.
264β
265```tsx
266const state = queryClient.getQueryState({ queryKey })
267console.log(state.dataUpdatedAt)
268```
269β
270**Options**
271β
272- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
273β
274## `queryClient.setQueriesData`
275β
276`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 existing query.
277β
278```tsx
279queryClient.setQueriesData(filters, updater)
280```
281β
282**Options**
283β
284- `filters: QueryFilters`: [Query Filters](../guides/filters#query-filters)
285 - if a filter is passed, queryKeys matching the filter will be updated
286- `updater: TQueryFnData | (oldData: TQueryFnData | undefined) => TQueryFnData`
287 - the [setQueryData](#queryclientsetquerydata) updater function or new data, will be called for each matching queryKey
288β
289## `queryClient.invalidateQueries`
290β
291The `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.
292β
293- If you **do not want active queries to refetch**, and simply be marked as invalid, you can use the `refetchType: 'none'` option.
294- If you **want inactive queries to refetch** as well, use the `refetchType: 'all'` option
295β
296```tsx
297await queryClient.invalidateQueries({
298 queryKey: ['posts'],
299 exact,
300 refetchType: 'active',
301}, { throwOnError, cancelRefetch })
302```
303β
304**Options**
305β
306- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
307 - `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
308 - `refetchType?: 'active' | 'inactive' | 'all' | 'none'`
309 - Defaults to `'active'`
310 - When set to `active`, only queries that match the refetch predicate and are actively being rendered via `useQuery` and friends will be refetched in the background.
311 - When set to `inactive`, only queries that match the refetch predicate and are NOT actively being rendered via `useQuery` and friends will be refetched in the background.
312 - When set to `all`, all queries that match the refetch predicate will be refetched in the background.
313 - When set to `none`, no queries will be refetched, and those that match the refetch predicate will be marked as invalid only.
314 - `refetchPage: (page: TData, index: number, allPages: TData[]) => boolean`
315 - Only for [Infinite Queries](../guides/infinite-queries#refetchpage)
316 - Use this function to specify which pages should be refetched
317- `options?: InvalidateOptions`:
318 - `throwOnError?: boolean`
319 - When set to `true`, this method will throw if any of the query refetch tasks fail.
320 - `cancelRefetch?: boolean`
321 - Defaults to `true`
322 - Per default, a currently running request will be cancelled before a new request is made
323 - When set to `false`, no refetch will be made if there is already a request running.
324β
325## `queryClient.refetchQueries`
326β
327The `refetchQueries` method can be used to refetch queries based on certain conditions.
328β
329Examples:
330β
331```tsx
332// refetch all queries:
333await queryClient.refetchQueries()
334β
335// refetch all stale queries:
336await queryClient.refetchQueries({ stale: true })
337β
338// refetch all active queries partially matching a query key:
339await queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' })
340β
341// refetch all active queries exactly matching a query key:
342await queryClient.refetchQueries({ queryKey: ['posts', 1], type: 'active', exact: true })
343```
344β
345**Options**
346β
347- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
348 - `refetchPage: (page: TData, index: number, allPages: TData[]) => boolean`
349 - Only for [Infinite Queries](../guides/infinite-queries#refetchpage)
350 - Use this function to specify which pages should be refetched
351- `options?: RefetchOptions`:
352 - `throwOnError?: boolean`
353 - When set to `true`, this method will throw if any of the query refetch tasks fail.
354 - `cancelRefetch?: boolean`
355 - Defaults to `true`
356 - Per default, a currently running request will be cancelled before a new request is made
357 - When set to `false`, no refetch will be made if there is already a request running.
358β
359**Returns**
360β
361This 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`
362β
363## `queryClient.cancelQueries`
364β
365The `cancelQueries` method can be used to cancel outgoing queries based on their query keys or any other functionally accessible property/state of the query.
366β
367This 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.
368β
369```tsx
370await queryClient.cancelQueries({ queryKey: ['posts'], exact: true })
371```
372β
373**Options**
374β
375- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
376β
377**Returns**
378β
379This method does not return anything
380β
381## `queryClient.removeQueries`
382β
383The `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.
384β
385```tsx
386queryClient.removeQueries({ queryKey, exact: true })
387```
388β
389**Options**
390β
391- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
392β
393**Returns**
394β
395This method does not return anything
396β
397## `queryClient.resetQueries`
398β
399The `resetQueries` method can be used to reset queries in the cache to their
400initial state based on their query keys or any other functionally accessible
401property/state of the query.
402β
403This will notify subscribers — unlike `clear`, which removes all
404subscribers — and reset the query to its pre-loaded state — unlike
405`invalidateQueries`. If a query has `initialData`, the query's data will be
406reset to that. If a query is active, it will be refetched.
407β
408```tsx
409queryClient.resetQueries({ queryKey, exact: true })
410```
411β
412**Options**
413β
414- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
415 - `refetchPage: (page: TData, index: number, allPages: TData[]) => boolean`
416 - Only for [Infinite Queries](../guides/infinite-queries#refetchpage)
417 - Use this function to specify which pages should be refetched
418- `options?: ResetOptions`:
419 - `throwOnError?: boolean`
420 - When set to `true`, this method will throw if any of the query refetch tasks fail.
421 - `cancelRefetch?: boolean`
422 - Defaults to `true`
423 - Per default, a currently running request will be cancelled before a new request is made
424 - When set to `false`, no refetch will be made if there is already a request running.
425β
426**Returns**
427β
428This method returns a promise that resolves when all active queries have been refetched.
429β
430## `queryClient.isFetching`
431β
432This `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)
433β
434```tsx
435if (queryClient.isFetching()) {
436 console.log('At least one query is fetching!')
437}
438```
439β
440TanStack Query also exports a handy [`useIsFetching`](../reference/useIsFetching) hook that will let you subscribe to this state in your components without creating a manual subscription to the query cache.
441β
442**Options**
443β
444- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
445β
446**Returns**
447β
448This method returns the number of fetching queries.
449β
450## `queryClient.isMutating`
451β
452This `isMutating` method returns an `integer` representing how many mutations, if any, in the cache are currently fetching.
453β
454```tsx
455if (queryClient.isMutating()) {
456 console.log('At least one mutation is fetching!')
457}
458```
459β
460TanStack Query also exports a handy [`useIsMutating`](../reference/useIsMutating) hook that will let you subscribe to this state in your components without creating a manual subscription to the mutation cache.
461β
462**Options**
463β
464- `filters: MutationFilters`: [Mutation Filters](../guides/filters#mutation-filters)
465β
466**Returns**
467β
468This method returns the number of fetching mutations.
469## `queryClient.getLogger`
470β
471The `getLogger` method returns the logger which have been set when creating the client.
472β
473```tsx
474const logger = queryClient.getLogger()
475```
476β
477## `queryClient.getDefaultOptions`
478β
479The `getDefaultOptions` method returns the default options which have been set when creating the client or with `setDefaultOptions`.
480β
481```tsx
482const defaultOptions = queryClient.getDefaultOptions()
483```
484β
485## `queryClient.setDefaultOptions`
486β
487The `setDefaultOptions` method can be used to dynamically set the default options for this queryClient. Previously defined default options will be overwritten.
488β
489```tsx
490queryClient.setDefaultOptions({
491 queries: {
492 staleTime: Infinity,
493 },
494})
495```
496β
497## `queryClient.getQueryDefaults`
498β
499The `getQueryDefaults` method returns the default options which have been set for specific queries:
500β
501```tsx
502const defaultOptions = queryClient.getQueryDefaults(['posts'])
503```
504β
505> Note that if several query defaults match the given query key, the **first** matching one is returned.
506> This could lead to unexpected behaviours. See [`setQueryDefaults`](#queryclientsetquerydefaults).
507β
508## `queryClient.setQueryDefaults`
509β
510`setQueryDefaults` can be used to set default options for specific queries:
511β
512```tsx
513queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts })
514β
515function Component() {
516 const { data } = useQuery({ queryKey: ['posts'] })
517}
518```
519β
520**Options**
521β
522- `queryKey: QueryKey`: [Query Keys](../guides/query-keys)
523- `options: QueryOptions`
524β
525> As stated in [`getQueryDefaults`](#queryclientgetquerydefaults), the order of registration of query defaults does matter.
526> Since the **first** matching defaults are returned by `getQueryDefaults`, the registration should be made in the following order: from the **least generic key** to the **most generic one**. This way, in case of specific key, the first matching one would be the expected one.
527β
528## `queryClient.getMutationDefaults`
529β
530The `getMutationDefaults` method returns the default options which have been set for specific mutations:
531β
532```tsx
533const defaultOptions = queryClient.getMutationDefaults(['addPost'])
534```
535β
536## `queryClient.setMutationDefaults`
537β
538`setMutationDefaults` can be used to set default options for specific mutations:
539β
540```tsx
541queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost })
542β
543function Component() {
544 const { data } = useMutation({ mutationKey: ['addPost'] })
545}
546```
547β
548**Options**
549β
550- `mutationKey: string | unknown[]`
551- `options: MutationOptions`
552β
553> Similar to [`setQueryDefaults`](#queryclientsetquerydefaults), the order of registration does matter here.
554β
555## `queryClient.getQueryCache`
556β
557The `getQueryCache` method returns the query cache this client is connected to.
558β
559```tsx
560const queryCache = queryClient.getQueryCache()
561```
562β
563## `queryClient.getMutationCache`
564β
565The `getMutationCache` method returns the mutation cache this client is connected to.
566β
567```tsx
568const mutationCache = queryClient.getMutationCache()
569```
570β
571## `queryClient.clear`
572β
573The `clear` method clears all connected caches.
574β
575```tsx
576queryClient.clear()
577```
578β
579## `queryClient.resumePausedMutations`
580β
581Can be used to resume mutations that have been paused because there was no network connection.
582β
583```tsx
584queryClient.resumePausedMutations()
585```