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

QueryClient.md

576 lines20.7 KB

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.getDefaultOptions`](#queryclientgetdefaultoptions)
44- [`queryClient.setDefaultOptions`](#queryclientsetdefaultoptions)
45- [`queryClient.getQueryDefaults`](#queryclientgetquerydefaults)
46- [`queryClient.setQueryDefaults`](#queryclientsetquerydefaults)
47- [`queryClient.getMutationDefaults`](#queryclientgetmutationdefaults)
48- [`queryClient.setMutationDefaults`](#queryclientsetmutationdefaults)
49- [`queryClient.getQueryCache`](#queryclientgetquerycache)
50- [`queryClient.getMutationCache`](#queryclientgetmutationcache)
51- [`queryClient.clear`](#queryclientclear)
52- [`queryClient.resumePausedMutations`](#queryclientresumepausedmutations)
53​
54**Options**
55​
56- `queryCache?: QueryCache`
57 - Optional
58 - The query cache this client is connected to.
59- `mutationCache?: MutationCache`
60 - Optional
61 - The mutation cache this client is connected to.
62- `defaultOptions?: DefaultOptions`
63 - Optional
64 - Define defaults for all queries and mutations using this queryClient.
65​
66## `queryClient.fetchQuery`
67​
68`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.
69​
70If 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.
71​
72> 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.
73​
74```tsx
75try {
76 const data = await queryClient.fetchQuery({ queryKey, queryFn })
77} catch (error) {
78 console.log(error)
80```
81​
82Specify a `staleTime` to only fetch when the data is older than a certain amount of time:
83​
84```tsx
85try {
86 const data = await queryClient.fetchQuery({
87 queryKey,
88 queryFn,
89 staleTime: 10000,
90 })
91} catch (error) {
92 console.log(error)
94```
95​
96**Options**
97​
98The options for `fetchQuery` are exactly the same as those of [`useQuery`](./framework/react/reference/useQuery), except the following: `enabled, refetchInterval, refetchIntervalInBackground, refetchOnWindowFocus, refetchOnReconnect, refetchOnMount, notifyOnChangeProps, throwOnError, select, suspense, placeholderData`; which are strictly for useQuery and useInfiniteQuery. You can check the [source code](https://github.com/TanStack/query/blob/7cd2d192e6da3df0b08e334ea1cf04cd70478827/packages/query-core/src/types.ts#L119) 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)
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, TPageParam>>`
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- `queryKey: QueryKey`: [Query Keys](./framework/react/guides/query-keys)
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](./framework/react/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 `gcTime` 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](./framework/react/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 _immutable_ 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- `queryKey: QueryKey`: [Query Keys](./framework/react/guides/query-keys)
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](./framework/react/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 {
299 queryKey: ['posts'],
300 exact,
301 refetchType: 'active',
302 },
303 { throwOnError, cancelRefetch },
305```
306​
307**Options**
308​
309- `filters?: QueryFilters`: [Query Filters](./framework/react/guides/filters#query-filters)
310 - `queryKey?: QueryKey`: [Query Keys](./framework/react/guides/query-keys)
311 - `refetchType?: 'active' | 'inactive' | 'all' | 'none'`
312 - Defaults to `'active'`
313 - 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.
314 - 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.
315 - When set to `all`, all queries that match the refetch predicate will be refetched in the background.
316 - When set to `none`, no queries will be refetched, and those that match the refetch predicate will be marked as invalid only.
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({
343 queryKey: ['posts', 1],
344 type: 'active',
345 exact: true,
346})
347```
348​
349**Options**
350​
351- `filters?: QueryFilters`: [Query Filters](./framework/react/guides/filters#query-filters)
352- `options?: RefetchOptions`:
353 - `throwOnError?: boolean`
354 - When set to `true`, this method will throw if any of the query refetch tasks fail.
355 - `cancelRefetch?: boolean`
356 - Defaults to `true`
357 - Per default, a currently running request will be cancelled before a new request is made
358 - When set to `false`, no refetch will be made if there is already a request running.
359​
360**Returns**
361​
362This 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`
363​
364## `queryClient.cancelQueries`
365​
366The `cancelQueries` method can be used to cancel outgoing queries based on their query keys or any other functionally accessible property/state of the query.
367​
368This 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.
369​
370```tsx
371await queryClient.cancelQueries({ queryKey: ['posts'], exact: true })
372```
373​
374**Options**
375​
376- `filters?: QueryFilters`: [Query Filters](./framework/react/guides/filters#query-filters)
377​
378**Returns**
379​
380This method does not return anything
381​
382## `queryClient.removeQueries`
383​
384The `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.
385​
386```tsx
387queryClient.removeQueries({ queryKey, exact: true })
388```
389​
390**Options**
391​
392- `filters?: QueryFilters`: [Query Filters](./framework/react/guides/filters#query-filters)
393​
394**Returns**
395​
396This method does not return anything
397​
398## `queryClient.resetQueries`
399​
400The `resetQueries` method can be used to reset queries in the cache to their
401initial state based on their query keys or any other functionally accessible
402property/state of the query.
403​
404This will notify subscribers &mdash; unlike `clear`, which removes all
405subscribers &mdash; and reset the query to its pre-loaded state &mdash; unlike
406`invalidateQueries`. If a query has `initialData`, the query's data will be
407reset to that. If a query is active, it will be refetched.
408​
409```tsx
410queryClient.resetQueries({ queryKey, exact: true })
411```
412​
413**Options**
414​
415- `filters?: QueryFilters`: [Query Filters](./framework/react/guides/filters#query-filters)
416- `options?: ResetOptions`:
417 - `throwOnError?: boolean`
418 - When set to `true`, this method will throw if any of the query refetch tasks fail.
419 - `cancelRefetch?: boolean`
420 - Defaults to `true`
421 - Per default, a currently running request will be cancelled before a new request is made
422 - When set to `false`, no refetch will be made if there is already a request running.
423​
424**Returns**
425​
426This method returns a promise that resolves when all active queries have been refetched.
427​
428## `queryClient.isFetching`
429​
430This `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)
431​
432```tsx
433if (queryClient.isFetching()) {
434 console.log('At least one query is fetching!')
436```
437​
438TanStack Query also exports a handy [`useIsFetching`](./framework/react/reference/useIsFetching) hook that will let you subscribe to this state in your components without creating a manual subscription to the query cache.
439​
440**Options**
441​
442- `filters?: QueryFilters`: [Query Filters](./framework/react/guides/filters#query-filters)
443​
444**Returns**
445​
446This method returns the number of fetching queries.
447​
448## `queryClient.isMutating`
449​
450This `isMutating` method returns an `integer` representing how many mutations, if any, in the cache are currently fetching.
451​
452```tsx
453if (queryClient.isMutating()) {
454 console.log('At least one mutation is fetching!')
456```
457​
458TanStack Query also exports a handy [`useIsMutating`](./framework/react/reference/useIsMutating) hook that will let you subscribe to this state in your components without creating a manual subscription to the mutation cache.
459​
460**Options**
461​
462- `filters: MutationFilters`: [Mutation Filters](./framework/react/guides/filters#mutation-filters)
463​
464**Returns**
465​
466This method returns the number of fetching mutations.
467​
468## `queryClient.getDefaultOptions`
469​
470The `getDefaultOptions` method returns the default options which have been set when creating the client or with `setDefaultOptions`.
471​
472```tsx
473const defaultOptions = queryClient.getDefaultOptions()
474```
475​
476## `queryClient.setDefaultOptions`
477​
478The `setDefaultOptions` method can be used to dynamically set the default options for this queryClient. Previously defined default options will be overwritten.
479​
480```tsx
481queryClient.setDefaultOptions({
482 queries: {
483 staleTime: Infinity,
484 },
485})
486```
487​
488## `queryClient.getQueryDefaults`
489​
490The `getQueryDefaults` method returns the default options which have been set for specific queries:
491​
492```tsx
493const defaultOptions = queryClient.getQueryDefaults(['posts'])
494```
495​
496> Note that if several query defaults match the given query key, the **first** matching one is returned.
497> This could lead to unexpected behaviours. See [`setQueryDefaults`](#queryclientsetquerydefaults).
498​
499## `queryClient.setQueryDefaults`
500​
501`setQueryDefaults` can be used to set default options for specific queries:
502​
503```tsx
504queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts })
505​
506function Component() {
507 const { data } = useQuery({ queryKey: ['posts'] })
509```
510​
511**Options**
512​
513- `queryKey: QueryKey`: [Query Keys](./framework/react/guides/query-keys)
514- `options: QueryOptions`
515​
516> As stated in [`getQueryDefaults`](#queryclientgetquerydefaults), the order of registration of query defaults does matter.
517> 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.
518​
519## `queryClient.getMutationDefaults`
520​
521The `getMutationDefaults` method returns the default options which have been set for specific mutations:
522​
523```tsx
524const defaultOptions = queryClient.getMutationDefaults(['addPost'])
525```
526​
527## `queryClient.setMutationDefaults`
528​
529`setMutationDefaults` can be used to set default options for specific mutations:
530​
531```tsx
532queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost })
533​
534function Component() {
535 const { data } = useMutation({ mutationKey: ['addPost'] })
537```
538​
539**Options**
540​
541- `mutationKey: unknown[]`
542- `options: MutationOptions`
543​
544> Similar to [`setQueryDefaults`](#queryclientsetquerydefaults), the order of registration does matter here.
545​
546## `queryClient.getQueryCache`
547​
548The `getQueryCache` method returns the query cache this client is connected to.
549​
550```tsx
551const queryCache = queryClient.getQueryCache()
552```
553​
554## `queryClient.getMutationCache`
555​
556The `getMutationCache` method returns the mutation cache this client is connected to.
557​
558```tsx
559const mutationCache = queryClient.getMutationCache()
560```
561​
562## `queryClient.clear`
563​
564The `clear` method clears all connected caches.
565​
566```tsx
567queryClient.clear()
568```
569​
570## `queryClient.resumePausedMutations`
571​
572Can be used to resume mutations that have been paused because there was no network connection.
573​
574```tsx
575queryClient.resumePausedMutations()
576```