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

QueryClient.md

458 lines14.6 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- [`fetchQuery`](#queryclientfetchquery)
27- [`fetchInfiniteQuery`](#queryclientfetchinfinitequery)
28- [`prefetchQuery`](#queryclientprefetchquery)
29- [`prefetchInfiniteQuery`](#queryclientprefetchinfinitequery)
30- [`getQueryData`](#queryclientgetquerydata)
31- [`setQueryData`](#queryclientsetquerydata)
32- [`getQueryState`](#queryclientgetquerystate)
33- [`invalidateQueries`](#queryclientinvalidatequeries)
34- [`refetchQueries`](#queryclientrefetchqueries)
35- [`cancelQueries`](#queryclientcancelqueries)
36- [`removeQueries`](#queryclientremovequeries)
37- [`resetQueries`](#queryclientresetqueries)
38- [`isFetching`](#queryclientisfetching)
39- [`getDefaultOptions`](#queryclientsetdefaultoptions)
40- [`setDefaultOptions`](#queryclientgetdefaultoptions)
41- [`getQueryDefaults`](#queryclientgetquerydefaults)
42- [`setQueryDefaults`](#queryclientsetquerydefaults)
43- [`getMutationDefaults`](#queryclientgetmutationdefaults)
44- [`setMutationDefaults`](#queryclientsetmutationdefaults)
45- [`getQueryCache`](#queryclientgetquerycache)
46- [`getMutationCache`](#queryclientgetmutationcache)
47- [`clear`](#queryclientclear)
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​
61## `queryClient.fetchQuery`
62​
63`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.
64​
65If 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.
66​
67> 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.
68​
69```js
70try {
71 const data = await queryClient.fetchQuery(queryKey, queryFn)
72} catch (error) {
73 console.log(error)
75```
76​
77Specify a `staleTime` to only fetch when the data is older than a certain amount of time:
78​
79```js
80try {
81 const data = await queryClient.fetchQuery(queryKey, queryFn, {
82 staleTime: 10000,
83 })
84} catch (error) {
85 console.log(error)
87```
88​
89**Options**
90​
91The 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.
92​
93**Returns**
94​
95- `Promise<TData>`
96​
97## `queryClient.fetchInfiniteQuery`
98​
99`fetchInfiniteQuery` is similar to `fetchQuery` but can be used to fetch and cache an infinite query.
100​
101```js
102try {
103 const data = await queryClient.fetchInfiniteQuery(queryKey, queryFn)
104 console.log(data.pages)
105} catch (error) {
106 console.log(error)
108```
109​
110**Options**
111​
112The options for `fetchInfiniteQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
113​
114**Returns**
115​
116- `Promise<InfiniteData<TData>>`
117​
118## `queryClient.prefetchQuery`
119​
120`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.
121​
122```js
123await queryClient.prefetchQuery(queryKey, queryFn)
124```
125​
126You can even use it with a default queryFn in your config!
127​
128```js
129await queryClient.prefetchQuery(queryKey)
130```
131​
132**Options**
133​
134The options for `prefetchQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
135​
136**Returns**
137​
138- `Promise<void>`
139 - 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.
140​
141## `queryClient.prefetchInfiniteQuery`
142​
143`prefetchInfiniteQuery` is similar to `prefetchQuery` but can be used to prefetch and cache an infinite query.
144​
145```js
146await queryClient.prefetchInfiniteQuery(queryKey, queryFn)
147```
148​
149**Options**
150​
151The options for `prefetchInfiniteQuery` are exactly the same as those of [`fetchQuery`](#queryclientfetchquery).
152​
153**Returns**
154​
155- `Promise<void>`
156 - 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.
157​
158## `queryClient.getQueryData`
159​
160`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.
161​
162```js
163const data = queryClient.getQueryData(queryKey)
164```
165​
166**Options**
167​
168- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
169- `filters?: QueryFilters`: [Query Filters](../guides/query-filters)
170​
171**Returns**
172​
173- `data: TData | undefined`
174 - The data for the cached query, or `undefined` if the query does not exist.
175​
176## `queryClient.setQueryData`
177​
178`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**.
179​
180> 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.
181​
182```js
183queryClient.setQueryData(queryKey, updater)
184```
185​
186**Options**
187​
188- `queryKey: QueryKey`: [Query Keys](../guides/query-keys)
189- `updater: unknown | (oldData: TData | undefined) => TData`
190 - If non-function is passed, the data will be updated to this value
191 - If a function is passed, it will receive the old data value and be expected to return a new one.
192​
193**Using an updater value**
194​
195```js
196setQueryData(queryKey, newData)
197```
198​
199**Using an updater function**
200​
201For convenience in syntax, you can also pass an updater function which receives the current data value and returns the new one:
202​
203```js
204setQueryData(queryKey, oldData => newData)
205```
206​
207## `queryClient.getQueryState`
208​
209`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.
210​
211```js
212const state = queryClient.getQueryState(queryKey)
213console.log(state.dataUpdatedAt)
214```
215​
216**Options**
217​
218- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
219- `filters?: QueryFilters`: [Query Filters](../guides/query-filters)
220​
221## `queryClient.invalidateQueries`
222​
223The `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.
224​
225- If you **do not want active queries to refetch**, and simply be marked as invalid, you can use the `refetchActive: false` option.
226- If you **want inactive queries to refetch** as well, use the `refetchInactive: true` option
227​
228```js
229await queryClient.invalidateQueries('posts', {
230 exact,
231 refetchActive: true,
232 refetchInactive: false
233}, { throwOnError })
234```
235​
236**Options**
237​
238- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
239- `filters?: QueryFilters`: [Query Filters](../guides/query-filters)
240 - `refetchActive: Boolean`
241 - Defaults to `true`
242 - 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.
243 - `refetchInactive: Boolean`
244 - Defaults to `false`
245 - 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
246- `refetchOptions?: RefetchOptions`:
247 - `throwOnError?: boolean`
248 - When set to `true`, this method will throw if any of the query refetch tasks fail.
249​
250## `queryClient.refetchQueries`
251​
252The `refetchQueries` method can be used to refetch queries based on certain conditions.
253​
254Examples:
255​
256```js
257// refetch all queries:
258await queryClient.refetchQueries()
259​
260// refetch all stale queries:
261await queryClient.refetchQueries({ stale: true })
262​
263// refetch all active queries partially matching a query key:
264await queryClient.refetchQueries(['posts'], { active: true })
265​
266// refetch all active queries exactly matching a query key:
267await queryClient.refetchQueries(['posts', 1], { active: true, exact: true })
268```
269​
270**Options**
271​
272- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
273- `filters?: QueryFilters`: [Query Filters](../guides/query-filters)
274- `refetchOptions?: RefetchOptions`:
275 - `throwOnError?: boolean`
276 - When set to `true`, this method will throw if any of the query refetch tasks fail.
277​
278**Returns**
279​
280This 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`
281​
282## `queryClient.cancelQueries`
283​
284The `cancelQueries` method can be used to cancel outgoing queries based on their query keys or any other functionally accessible property/state of the query.
285​
286This 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.
287​
288```js
289await queryClient.cancelQueries('posts', { exact: true })
290```
291​
292**Options**
293​
294- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
295- `filters?: QueryFilters`: [Query Filters](../guides/query-filters)
296​
297**Returns**
298​
299This method does not return anything
300​
301## `queryClient.removeQueries`
302​
303The `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.
304​
305```js
306queryClient.removeQueries(queryKey, { exact: true })
307```
308​
309**Options**
310​
311- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
312- `filters?: QueryFilters`: [Query Filters](../guides/query-filters)
313​
314**Returns**
315​
316This method does not return anything
317​
318## `queryClient.resetQueries`
319​
320The `resetQueries` method can be used to reset queries in the cache to their
321initial state based on their query keys or any other functionally accessible
322property/state of the query.
323​
324This will notify subscribers &mdash; unlike `clear`, which removes all
325subscribers &mdash; and reset the query to its pre-loaded state &mdash; unlike
326`invalidateQueries`. If a query has `initialData`, the query's data will be
327reset to that. If a query is active, it will be refetched.
328​
329```js
330queryClient.resetQueries(queryKey, { exact: true })
331```
332​
333**Options**
334​
335- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
336- `filters?: QueryFilters`: [Query Filters](../guides/query-filters)
337- `resetOptions?: ResetOptions`:
338 - `throwOnError?: boolean`
339 - When set to `true`, this method will throw if any of the query refetch tasks fail.
340​
341**Returns**
342​
343This method returns a promise that resolves when all active queries have been refetched.
344​
345## `queryClient.isFetching`
346​
347This `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)
348​
349```js
350if (queryClient.isFetching()) {
351 console.log('At least one query is fetching!')
353```
354​
355React 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.
356​
357**Options**
358​
359- `queryKey?: QueryKey`: [Query Keys](../guides/query-keys)
360- `filters?: QueryFilters`: [Query Filters](../guides/query-filters)
361​
362**Returns**
363​
364This method returns the number of fetching queries.
365​
366## `queryClient.getDefaultOptions`
367​
368The `getDefaultOptions` method returns the default options which have been set when creating the client or with `setDefaultOptions`.
369​
370```js
371const defaultOptions = queryClient.getDefaultOptions()
372```
373​
374## `queryClient.setDefaultOptions`
375​
376The `setDefaultOptions` method can be used to dynamically set the default options for this queryClient.
377​
378```js
379queryClient.setDefaultOptions({
380 queries: {
381 staleTime: Infinity,
382 },
383})
384```
385​
386## `queryClient.getQueryDefaults`
387​
388The `getQueryDefaults` method returns the default options which have been set for specific queries:
389​
390```js
391const defaultOptions = queryClient.getQueryDefaults('posts')
392```
393​
394## `queryClient.setQueryDefaults`
395​
396`setQueryDefaults` can be used to set default options for specific queries:
397​
398```js
399queryClient.setQueryDefaults('posts', { queryFn: fetchPosts })
400​
401function Component() {
402 const { data } = useQuery('posts')
404```
405​
406**Options**
407​
408- `queryKey: QueryKey`: [Query Keys](../guides/query-keys)
409- `options: QueryOptions`
410​
411## `queryClient.getMutationDefaults`
412​
413The `getMutationDefaults` method returns the default options which have been set for specific mutations:
414​
415```js
416const defaultOptions = queryClient.getMutationDefaults('addPost')
417```
418​
419## `queryClient.setMutationDefaults`
420​
421`setMutationDefaults` can be used to set default options for specific mutations:
422​
423```js
424queryClient.setMutationDefaults('addPost', { mutationFn: addPost })
425​
426function Component() {
427 const { data } = useMutation('addPost')
429```
430​
431**Options**
432​
433- `mutationKey: string | unknown[]`
434- `options: MutationOptions`
435​
436## `queryClient.getQueryCache`
437​
438The `getQueryCache` method returns the query cache this client is connected to.
439​
440```js
441const queryCache = queryClient.getQueryCache()
442```
443​
444## `queryClient.getMutationCache`
445​
446The `getMutationCache` method returns the mutation cache this client is connected to.
447​
448```js
449const mutationCache = queryClient.getMutationCache()
450```
451​
452## `queryClient.clear`
453​
454The `clear` method clears all connected caches.
455​
456```js
457queryClient.clear()
458```