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

QueryClient.md

519 lines19.3 KB

1---
2id: QueryClient
3title: QueryClient
4---
5​
6The `QueryClient` can be used to interact with a cache:
7​
8```tsx
9import { QueryClient } from '@tanstack/react-query'
10​
11const queryClient = new QueryClient({
12 defaultOptions: {
13 queries: {
14 staleTime: Infinity,
15 },
16 },
17})
18​
19await queryClient.query({ queryKey: ['posts'], queryFn: fetchPosts })
20```
21​
22Its available methods are:
23​
24- [`queryClient.query`](#queryclient-query)
25- [`queryClient.infiniteQuery`](#queryclient-infinitequery)
26- [`queryClient.getQueryData`](#queryclient-getquerydata)
27- [`queryClient.getQueriesData`](#queryclient-getqueriesdata)
28- [`queryClient.setQueryData`](#queryclient-setquerydata)
29- [`queryClient.getQueryState`](#queryclient-getquerystate)
30- [`queryClient.setQueriesData`](#queryclient-setqueriesdata)
31- [`queryClient.invalidateQueries`](#queryclient-invalidatequeries)
32- [`queryClient.refetchQueries`](#queryclient-refetchqueries)
33- [`queryClient.cancelQueries`](#queryclient-cancelqueries)
34- [`queryClient.removeQueries`](#queryclient-removequeries)
35- [`queryClient.resetQueries`](#queryclient-resetqueries)
36- [`queryClient.isFetching`](#queryclient-isfetching)
37- [`queryClient.isMutating`](#queryclient-ismutating)
38- [`queryClient.getDefaultOptions`](#queryclient-getdefaultoptions)
39- [`queryClient.setDefaultOptions`](#queryclient-setdefaultoptions)
40- [`queryClient.getQueryDefaults`](#queryclient-getquerydefaults)
41- [`queryClient.setQueryDefaults`](#queryclient-setquerydefaults)
42- [`queryClient.getMutationDefaults`](#queryclient-getmutationdefaults)
43- [`queryClient.setMutationDefaults`](#queryclient-setmutationdefaults)
44- [`queryClient.getQueryCache`](#queryclient-getquerycache)
45- [`queryClient.getMutationCache`](#queryclient-getmutationcache)
46- [`queryClient.clear`](#queryclient-clear)
47- [`queryClient.resumePausedMutations`](#queryclient-resumepausedmutations)
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 - You can also define defaults to be used for [hydration](../framework/react/reference/hydration.md)
61​
62## `queryClient.query`
63​
64`query` is an asynchronous method that can be used to fetch and cache a query. It will either resolve with the data or throw with an error.
65​
66If 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.
67​
68```tsx
69try {
70 const data = await queryClient.query({ queryKey, queryFn })
71} catch (error) {
72 console.log(error)
74```
75​
76Specify a `staleTime` to only fetch when the data is older than a certain amount of time:
77​
78```tsx
79try {
80 const data = await queryClient.query({
81 queryKey,
82 queryFn,
83 staleTime: 10000,
84 select: (data) => data.items,
85 })
86} catch (error) {
87 console.log(error)
89```
90​
91**Options**
92​
93The options for `query` are exactly the same as those of [`useQuery`](../framework/react/reference/useQuery.md), except the following: `enabled, refetchInterval, refetchIntervalInBackground, refetchOnWindowFocus, refetchOnReconnect, refetchOnMount, notifyOnChangeProps, throwOnError, 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.
94​
95**Returns**
96​
97- `Promise<TData>`
98​
99## `queryClient.infiniteQuery`
100​
101`infiniteQuery` is similar to `query` but can be used to fetch and cache an infinite query.
102​
103```tsx
104try {
105 const data = await queryClient.infiniteQuery({ queryKey, queryFn })
106 console.log(data.pages)
107} catch (error) {
108 console.log(error)
110```
111​
112**Options**
113​
114The options for `infiniteQuery` are exactly the same as those of [`query`](#queryclient-query), with the addition of `initialPageParam`, `pages` and `getNextPageParam` options from [`useInfiniteQuery`](../framework/react/reference/useInfiniteQuery.md).
115​
116**Returns**
117​
118- `Promise<InfiniteData<TData, TPageParam>>`
119​
120## `queryClient.getQueriesData`
121​
122`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.
123​
124```tsx
125const data = queryClient.getQueriesData(filters)
126```
127​
128**Options**
129​
130- `filters: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
131 - if a filter is passed, the data with queryKeys matching the filter will be returned
132​
133**Returns**
134​
135- `[queryKey: QueryKey, data: TQueryFnData | undefined][]`
136 - 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.
137​
138**Caveats**
139​
140Because 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.
141​
142This distinction is more a "convenience" for ts devs that know which structure will be returned.
143​
144## `queryClient.setQueryData`
145​
146`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 within the default `gcTime`, the query will be garbage collected. If the default `gcTime` has not been configured, it defaults to 5 minutes.** To update multiple queries at once and match query keys partially, you need to use [`queryClient.setQueriesData`](#queryclient-setqueriesdata) instead.
147​
148> The difference between using `setQueryData` and `query` 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 `query` to handle the asynchronous fetch.
149​
150```tsx
151queryClient.setQueryData(queryKey, updater)
152```
153​
154**Options**
155​
156- `queryKey: QueryKey`: [Query Keys](../framework/react/guides/query-keys.md)
157- `updater: TQueryFnData | undefined | ((oldData: TQueryFnData | undefined) => TQueryFnData | undefined)`
158 - If non-function is passed, the data will be updated to this value
159 - If a function is passed, it will receive the old data value and be expected to return a new one.
160​
161**Using an updater value**
162​
163```tsx
164setQueryData(queryKey, newData)
165```
166​
167If the value is `undefined`, the query data is not updated.
168​
169**Using an updater function**
170​
171For convenience in syntax, you can also pass an updater function which receives the current data value and returns the new one:
172​
173```tsx
174setQueryData(queryKey, (oldData) => newData)
175```
176​
177If 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.
178​
179**Immutability**
180​
181Updates 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.
182​
183## `queryClient.getQueryState`
184​
185`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.
186​
187```tsx
188const state = queryClient.getQueryState(queryKey)
189console.log(state.dataUpdatedAt)
190```
191​
192**Options**
193​
194- `queryKey: QueryKey`: [Query Keys](../framework/react/guides/query-keys.md)
195​
196## `queryClient.setQueriesData`
197​
198`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`](#queryclient-setquerydata) is called for each existing query.
199​
200```tsx
201queryClient.setQueriesData(filters, updater)
202```
203​
204**Options**
205​
206- `filters: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
207 - if a filter is passed, queryKeys matching the filter will be updated
208- `updater: TQueryFnData | (oldData: TQueryFnData | undefined) => TQueryFnData`
209 - the [setQueryData](#queryclient-setquerydata) updater function or new data, will be called for each matching queryKey
210​
211## `queryClient.invalidateQueries`
212​
213The `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.
214​
215- If you **do not want active queries to refetch**, and simply be marked as invalid, you can use the `refetchType: 'none'` option.
216- If you **want inactive queries to refetch** as well, use the `refetchType: 'all'` option
217- For refetching, [queryClient.refetchQueries](#queryclient-refetchqueries) is called.
218​
219```tsx
220await queryClient.invalidateQueries(
221 {
222 queryKey: ['posts'],
223 exact,
224 refetchType: 'active',
225 },
226 { throwOnError, cancelRefetch },
228```
229​
230**Options**
231​
232- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
233 - `queryKey?: QueryKey`: [Query Keys](../framework/react/guides/query-keys.md)
234 - `refetchType?: 'active' | 'inactive' | 'all' | 'none'`
235 - Defaults to `'active'`
236 - 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.
237 - 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.
238 - When set to `all`, all queries that match the refetch predicate will be refetched in the background.
239 - When set to `none`, no queries will be refetched, and those that match the refetch predicate will be marked as invalid only.
240- `options?: InvalidateOptions`:
241 - `throwOnError?: boolean`
242 - When set to `true`, this method will throw if any of the query refetch tasks fail.
243 - `cancelRefetch?: boolean`
244 - Defaults to `true`
245 - Per default, a currently running request will be cancelled before a new request is made
246 - When set to `false`, no refetch will be made if there is already a request running.
247​
248**Notes**
249​
250- Unlike [`refetchQueries`](#queryclient-refetchqueries), `invalidateQueries` marks matching queries as invalidated and then refetches `active` queries (unless otherwise specified with the `refetchType` option).
251- Unlike [`removeQueries`](#queryclient-removequeries), `invalidateQueries` keeps matching queries in the cache.
252​
253## `queryClient.refetchQueries`
254​
255The `refetchQueries` method can be used to refetch queries based on certain conditions.
256​
257Examples:
258​
259```tsx
260// refetch all queries:
261await queryClient.refetchQueries()
262​
263// refetch all stale queries:
264await queryClient.refetchQueries({ stale: true })
265​
266// refetch all active queries partially matching a query key:
267await queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' })
268​
269// refetch all active queries exactly matching a query key:
270await queryClient.refetchQueries({
271 queryKey: ['posts', 1],
272 type: 'active',
273 exact: true,
274})
275```
276​
277**Options**
278​
279- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
280- `options?: RefetchOptions`:
281 - `throwOnError?: boolean`
282 - When set to `true`, this method will throw if any of the query refetch tasks fail.
283 - `cancelRefetch?: boolean`
284 - Defaults to `true`
285 - Per default, a currently running request will be cancelled before a new request is made
286 - When set to `false`, no refetch will be made if there is already a request running.
287​
288**Returns**
289​
290This 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`
291​
292**Notes**
293​
294- Queries that are "disabled" because they only have disabled Observers will never be refetched.
295- Queries that are "static" because they only have Observers with a Static StaleTime will never be refetched.
296- Unlike [`invalidateQueries`](#queryclient-invalidatequeries), `refetchQueries` refetches all matching queries.
297​
298## `queryClient.cancelQueries`
299​
300The `cancelQueries` method can be used to cancel outgoing queries based on their query keys or any other functionally accessible property/state of the query.
301​
302This 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.
303​
304```tsx
305await queryClient.cancelQueries(
306 { queryKey: ['posts'], exact: true },
307 { silent: true },
309```
310​
311**Options**
312​
313- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
314- `cancelOptions?: CancelOptions`: [Cancel Options](../framework/react/guides/query-cancellation.md#cancel-options)
315​
316**Returns**
317​
318This method does not return anything
319​
320## `queryClient.removeQueries`
321​
322The `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.
323​
324```tsx
325queryClient.removeQueries({ queryKey, exact: true })
326```
327​
328**Options**
329​
330- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
331​
332**Returns**
333​
334This method does not return anything
335​
336**Notes**
337​
338- Unlike [`invalidateQueries`](#queryclient-invalidatequeries) or [`refetchQueries`](#queryclient-refetchqueries), `removeQueries` removes matching queries from the cache instead of refetching them.
339​
340## `queryClient.resetQueries`
341​
342The `resetQueries` method can be used to reset queries in the cache to their
343initial state based on their query keys or any other functionally accessible
344property/state of the query.
345​
346This will notify subscribers &mdash; unlike `clear`, which removes all
347subscribers &mdash; and reset the query to its pre-loaded state &mdash; unlike
348`invalidateQueries`. If a query has `initialData`, the query's data will be
349reset to that. If a query is active, it will be refetched.
350​
351```tsx
352queryClient.resetQueries({ queryKey, exact: true })
353```
354​
355**Options**
356​
357- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
358- `options?: ResetOptions`:
359 - `throwOnError?: boolean`
360 - When set to `true`, this method will throw if any of the query refetch tasks fail.
361 - `cancelRefetch?: boolean`
362 - Defaults to `true`
363 - Per default, a currently running request will be cancelled before a new request is made
364 - When set to `false`, no refetch will be made if there is already a request running.
365​
366**Returns**
367​
368This method returns a promise that resolves when all active queries have been refetched.
369​
370## `queryClient.isFetching`
371​
372This `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)
373​
374```tsx
375if (queryClient.isFetching()) {
376 console.log('At least one query is fetching!')
378```
379​
380TanStack Query also exports a handy [`useIsFetching`](../framework/react/reference/useIsFetching.md) hook that will let you subscribe to this state in your components without creating a manual subscription to the query cache.
381​
382**Options**
383​
384- `filters?: QueryFilters`: [Query Filters](../framework/react/guides/filters.md#query-filters)
385​
386**Returns**
387​
388This method returns the number of fetching queries.
389​
390## `queryClient.isMutating`
391​
392This `isMutating` method returns an `integer` representing how many mutations, if any, in the cache are currently fetching.
393​
394```tsx
395if (queryClient.isMutating()) {
396 console.log('At least one mutation is fetching!')
398```
399​
400TanStack Query also exports a handy [`useIsMutating`](../framework/react/reference/useIsMutating.md) hook that will let you subscribe to this state in your components without creating a manual subscription to the mutation cache.
401​
402**Options**
403​
404- `filters: MutationFilters`: [Mutation Filters](../framework/react/guides/filters.md#mutation-filters)
405​
406**Returns**
407​
408This method returns the number of fetching mutations.
409​
410## `queryClient.getDefaultOptions`
411​
412The `getDefaultOptions` method returns the default options which have been set when creating the client or with `setDefaultOptions`.
413​
414```tsx
415const defaultOptions = queryClient.getDefaultOptions()
416```
417​
418## `queryClient.setDefaultOptions`
419​
420The `setDefaultOptions` method can be used to dynamically set the default options for this queryClient. Previously defined default options will be overwritten.
421​
422```tsx
423queryClient.setDefaultOptions({
424 queries: {
425 staleTime: Infinity,
426 },
427})
428```
429​
430## `queryClient.getQueryDefaults`
431​
432The `getQueryDefaults` method returns the default options which have been set for specific queries:
433​
434```tsx
435const defaultOptions = queryClient.getQueryDefaults(['posts'])
436```
437​
438> Note that if several query defaults match the given query key, they will be merged together based on the order of registration.
439> See [`setQueryDefaults`](#queryclient-setquerydefaults).
440​
441## `queryClient.setQueryDefaults`
442​
443`setQueryDefaults` can be used to set default options for specific queries:
444​
445```tsx
446queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts })
447​
448function Component() {
449 const { data } = useQuery({ queryKey: ['posts'] })
451```
452​
453**Options**
454​
455- `queryKey: QueryKey`: [Query Keys](../framework/react/guides/query-keys.md)
456- `options: QueryOptions`
457​
458> As stated in [`getQueryDefaults`](#queryclient-getquerydefaults), the order of registration of query defaults does matter.
459> Since the matching defaults are merged by `getQueryDefaults`, the registration should be made in the following order: from the **most generic key** to the **least generic one** .
460> This way, more specific defaults will override more generic defaults.
461​
462## `queryClient.getMutationDefaults`
463​
464The `getMutationDefaults` method returns the default options which have been set for specific mutations:
465​
466```tsx
467const defaultOptions = queryClient.getMutationDefaults(['addPost'])
468```
469​
470## `queryClient.setMutationDefaults`
471​
472`setMutationDefaults` can be used to set default options for specific mutations:
473​
474```tsx
475queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost })
476​
477function Component() {
478 const { data } = useMutation({ mutationKey: ['addPost'] })
480```
481​
482**Options**
483​
484- `mutationKey: unknown[]`
485- `options: MutationOptions`
486​
487> Similar to [`setQueryDefaults`](#queryclient-setquerydefaults), the order of registration does matter here.
488​
489## `queryClient.getQueryCache`
490​
491The `getQueryCache` method returns the query cache this client is connected to.
492​
493```tsx
494const queryCache = queryClient.getQueryCache()
495```
496​
497## `queryClient.getMutationCache`
498​
499The `getMutationCache` method returns the mutation cache this client is connected to.
500​
501```tsx
502const mutationCache = queryClient.getMutationCache()
503```
504​
505## `queryClient.clear`
506​
507The `clear` method clears all connected caches.
508​
509```tsx
510queryClient.clear()
511```
512​
513## `queryClient.resumePausedMutations`
514​
515Can be used to resume mutations that have been paused because there was no network connection.
516​
517```tsx
518queryClient.resumePausedMutations()
519```