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

queryClient.ts

1,176 lines39.8 KB

1import {
2 functionalUpdate,
3 hashKey,
4 hashQueryKeyByOptions,
5 noop,
6 partialMatchKey,
7 resolveQueryValue,
8 skipToken,
9} from './utils'
10import { QueryCache } from './queryCache'
11import { MutationCache } from './mutationCache'
12import { focusManager } from './focusManager'
13import { onlineManager } from './onlineManager'
14import { notifyManager } from './notifyManager'
15import type {
16 CancelOptions,
17 DefaultError,
18 DefaultOptions,
19 DefaultedQueryObserverOptions,
20 EnsureInfiniteQueryDataOptions,
21 EnsureQueryDataOptions,
22 FetchInfiniteQueryOptions,
23 FetchQueryOptions,
24 InferDataFromTag,
25 InferErrorFromTag,
26 InfiniteData,
27 InfiniteQueryExecuteOptions,
28 InvalidateOptions,
29 InvalidateQueryFilters,
30 MutationKey,
31 MutationObserverOptions,
32 MutationOptions,
33 OmitKeyof,
34 QueryClientConfig,
35 QueryExecuteOptions,
36 QueryKey,
37 QueryObserverOptions,
38 QueryOptions,
39 RefetchOptions,
40 RefetchQueryFilters,
41 ResetOptions,
42 SetDataOptions,
43} from './types'
44import type { QueryState } from './query'
45import type { MutationFilters, QueryFilters, Updater } from './utils'
46​
47// TYPES
48​
49interface QueryDefaults {
50 queryKey: QueryKey
51 defaultOptions: OmitKeyof<QueryOptions<any, any, any>, 'queryKey'>
53​
54interface MutationDefaults {
55 mutationKey: MutationKey
56 defaultOptions: MutationOptions<any, any, any, any>
58​
59// CLASS
60​
61/**
62 * `QueryClient` is used to interact with a cache of queries and mutations. It owns a
63 * `QueryCache` and a `MutationCache` (creating default ones if none are passed in) and holds
64 * the default options that are applied to queries and mutations created through it.
65 * @example
66 * ```ts
67 * const queryClient = new QueryClient({
68 * defaultOptions: {
69 * queries: {
70 * staleTime: Infinity,
71 * },
72 * },
73 * })
74 *
75 * await queryClient.query({ queryKey: ['posts'], queryFn: fetchPosts })
76 * ```
77 */
78export class QueryClient {
79 #queryCache: QueryCache
80 #mutationCache: MutationCache
81 #defaultOptions: DefaultOptions
82 #queryDefaults: Map<string, QueryDefaults>
83 #mutationDefaults: Map<string, MutationDefaults>
84 #mountCount: number
85 #unsubscribeFocus?: () => void
86 #unsubscribeOnline?: () => void
87​
88 constructor(config: QueryClientConfig = {}) {
89 this.#queryCache = config.queryCache || new QueryCache()
90 this.#mutationCache = config.mutationCache || new MutationCache()
91 this.#defaultOptions = config.defaultOptions || {}
92 this.#queryDefaults = new Map()
93 this.#mutationDefaults = new Map()
94 this.#mountCount = 0
95 }
96​
97 /**
98 * Called by a framework adapter's `QueryClientProvider`-equivalent when it mounts, to start
99 * listening for focus/online events and resume paused mutations. Ref-counted via an internal
100 * mount count, so nested or multiple providers sharing the same `QueryClient` don't tear down
101 * the shared listeners until the last one unmounts.
102 */
103 mount(): void {
104 this.#mountCount++
105 if (this.#mountCount !== 1) return
106​
107 this.#unsubscribeFocus = focusManager.subscribe(async (focused) => {
108 if (focused) {
109 await this.resumePausedMutations()
110 this.#queryCache.onFocus()
111 }
112 })
113 this.#unsubscribeOnline = onlineManager.subscribe(async (online) => {
114 if (online) {
115 await this.resumePausedMutations()
116 this.#queryCache.onOnline()
117 }
118 })
119 }
120​
121 /**
122 * The inverse of {@link QueryClient#mount} β€” called by a framework adapter's
123 * `QueryClientProvider`-equivalent when it unmounts. Only tears down the focus/online
124 * listeners once the mount count returns to `0`.
125 */
126 unmount(): void {
127 this.#mountCount--
128 if (this.#mountCount !== 0) return
129​
130 this.#unsubscribeFocus?.()
131 this.#unsubscribeFocus = undefined
132​
133 this.#unsubscribeOnline?.()
134 this.#unsubscribeOnline = undefined
135 }
136​
137 /**
138 * Returns the number of queries in the cache that are currently fetching, optionally
139 * matching a set of filters. This includes background-fetching, loading new pages, and
140 * loading more infinite query results.
141 * @param filters - Narrows down which fetching queries are counted. Without filters, every
142 * fetching query is counted.
143 * @returns The number of matching queries whose `fetchStatus` is `'fetching'`.
144 * @example
145 * ```ts
146 * if (queryClient.isFetching()) {
147 * console.log('At least one query is fetching!')
148 * }
149 * ```
150 */
151 isFetching(filters?: Omit<QueryFilters, 'fetchStatus'>): number {
152 return this.#queryCache.findAll({ ...filters, fetchStatus: 'fetching' })
153 .length
154 }
155​
156 /**
157 * Returns the number of mutations in the cache that are currently pending, optionally
158 * matching a set of filters.
159 * @param filters - Narrows down which pending mutations are counted. Without filters, every
160 * pending mutation is counted.
161 * @returns The number of matching mutations whose `status` is `'pending'`.
162 * @example
163 * ```ts
164 * if (queryClient.isMutating()) {
165 * console.log('At least one mutation is pending!')
166 * }
167 * ```
168 */
169 isMutating<
170 TMutationFilters extends MutationFilters<any, any> = MutationFilters<
171 any,
172 any
173 >,
174 >(filters?: NoInfer<Omit<TMutationFilters, 'status'>>): number {
175 return this.#mutationCache.findAll({ ...filters, status: 'pending' }).length
176 }
177​
178 /**
179 * Imperative (non-reactive) way to retrieve data for a QueryKey.
180 * Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates.
181 *
182 * Hint: Do not use this function inside a component, because it won't receive updates.
183 * Use `useQuery` to create a `QueryObserver` that subscribes to changes.
184 * @param queryKey - The query key of the query to read.
185 * @returns The cached data for the query, or `undefined` if no query with this key has been observed yet.
186 * @see {@link QueryClient#getQueriesData}
187 */
188 getQueryData<
189 TQueryFnData = unknown,
190 TTaggedQueryKey extends QueryKey = QueryKey,
191 TInferredQueryFnData = InferDataFromTag<TQueryFnData, TTaggedQueryKey>,
192 >(queryKey: TTaggedQueryKey): TInferredQueryFnData | undefined {
193 const options = this.defaultQueryOptions({ queryKey })
194​
195 return this.#queryCache.get<TInferredQueryFnData>(options.queryHash)?.state
196 .data
197 }
198​
199 /**
200 * Returns the cached data of a query, or fetches it if there is none. With `revalidateIfStale`,
201 * stale cached data is also refetched in the background.
202 * @param options - The query options. If the query has no cached data yet, it is fetched with
203 * these options.
204 * @returns A promise that resolves to the cached data, or to the fetched data if nothing was
205 * cached yet.
206 * @deprecated Use queryClient.query({ ...options, staleTime: 'static' }) instead. This method will be removed in the next major version.
207 */
208 ensureQueryData<
209 TQueryFnData,
210 TError = DefaultError,
211 TData = TQueryFnData,
212 TQueryKey extends QueryKey = QueryKey,
213 >(
214 options: EnsureQueryDataOptions<TQueryFnData, TError, TData, TQueryKey>,
215 ): Promise<TData> {
216 const defaultedOptions = this.defaultQueryOptions(options)
217 const query = this.#queryCache.build(this, defaultedOptions)
218 const cachedData = query.state.data
219​
220 if (cachedData === undefined) {
221 // oxlint-disable-next-line tanstack-query/no-restricted-syntax
222 return this.fetchQuery(options)
223 }
224​
225 if (
226 options.revalidateIfStale &&
227 query.isStaleByTime(resolveQueryValue(defaultedOptions.staleTime, query))
228 ) {
229 // oxlint-disable-next-line tanstack-query/no-restricted-syntax
230 void this.prefetchQuery(defaultedOptions)
231 }
232​
233 return Promise.resolve(cachedData)
234 }
235​
236 /**
237 * Imperative (non-reactive) way to retrieve the cached data of multiple queries at once.
238 * Only queries matching the given filters are returned; if none match, an empty array is
239 * returned.
240 *
241 * Because the matched queries can hold data of different shapes (e.g. a broad filter can match
242 * queries with unrelated data types), the `TQueryFnData` generic defaults to `unknown` rather
243 * than being inferred. Passing a more specific type is a convenience for call sites that know
244 * every matched query holds the same shape β€” it is not checked against the actual cache
245 * contents.
246 * @param filters - The filters that select which queries to read.
247 * @returns An array of query key and data pairs. The data is `undefined` for a query with no cached data.
248 * @see {@link QueryClient#getQueryData}
249 * @example
250 * ```ts
251 * const data = queryClient.getQueriesData({ queryKey: ['posts'] })
252 * ```
253 */
254 getQueriesData<
255 TQueryFnData = unknown,
256 TQueryFilters extends QueryFilters<any> = QueryFilters,
257 >(filters: TQueryFilters): Array<[QueryKey, TQueryFnData | undefined]> {
258 return this.#queryCache.findAll(filters).map(({ queryKey, state }) => {
259 const data = state.data as TQueryFnData | undefined
260 return [queryKey, data]
261 })
262 }
263​
264 /**
265 * Synchronous way to immediately update a query's cached data. If the updater (or the value
266 * passed) resolves to `undefined`, the cache is left untouched and no query is created;
267 * otherwise, if the query does not exist yet, it will be created. To update multiple queries
268 * at once by partially matching query keys, use {@link QueryClient#setQueriesData} instead.
269 *
270 * Updates must be performed immutably: do not mutate `oldData`, or data previously retrieved
271 * via {@link QueryClient#getQueryData}, in place.
272 * @param queryKey - The query key to set data for.
273 * @param updater - Either the new data, or a function that receives the current data (which
274 * may be `undefined`) and returns the new data.
275 * @param options - Set `updatedAt` to override the timestamp the written data is recorded with.
276 * @returns The data that was written, or `undefined` if the updater returned `undefined` β€” in that case
277 * the write is skipped and the cache is left unchanged.
278 * @example
279 * ```ts
280 * queryClient.setQueryData(['posts'], newPosts)
281 *
282 * // Or, using an updater function that receives the current data:
283 * queryClient.setQueryData(['posts'], (oldPosts) => [...oldPosts, newPost])
284 * ```
285 */
286 setQueryData<
287 TQueryFnData = unknown,
288 TTaggedQueryKey extends QueryKey = QueryKey,
289 TInferredQueryFnData = InferDataFromTag<TQueryFnData, TTaggedQueryKey>,
290 >(
291 queryKey: TTaggedQueryKey,
292 updater: Updater<
293 InferDataFromTag<NoInfer<TQueryFnData>, TTaggedQueryKey> | undefined,
294 NoInfer<TInferredQueryFnData> | undefined
295 >,
296 options?: SetDataOptions,
297 ): NoInfer<TInferredQueryFnData> | undefined {
298 const defaultedOptions = this.defaultQueryOptions<
299 any,
300 any,
301 unknown,
302 any,
303 QueryKey
304 >({ queryKey })
305​
306 const query = this.#queryCache.get<
307 InferDataFromTag<NoInfer<TQueryFnData>, TTaggedQueryKey>
308 >(defaultedOptions.queryHash)
309 const prevData = query?.state.data
310 const data = functionalUpdate(updater, prevData)
311​
312 if (data === undefined) {
313 return undefined
314 }
315​
316 return this.#queryCache
317 .build(this, defaultedOptions)
318 .setData(data, { ...options, manual: true })
319 }
320​
321 /**
322 * Synchronous way to immediately update the cached data of multiple queries at once, using
323 * filters or partial query key matching. Only queries that already exist and match the given
324 * filters are updated; no new cache entries are created. Internally this calls
325 * {@link QueryClient#setQueryData} for each matching query.
326 * @param filters - The filters that select which existing queries to update.
327 * @param updater - Either the new data, or a function that receives each matched query's current
328 * data (which may be `undefined`) and returns the new data.
329 * @param options - Set `updatedAt` to override the timestamp the written data is recorded with.
330 * @returns One `[queryKey, data]` tuple per matched query, in the same shape and with the same
331 * `undefined` case as {@link QueryClient#setQueryData}.
332 * @example
333 * ```ts
334 * queryClient.setQueriesData({ queryKey: ['posts'] }, (oldPosts) =>
335 * oldPosts ? oldPosts.filter((post) => post.id !== deletedId) : oldPosts,
336 * )
337 * ```
338 */
339 setQueriesData<
340 TQueryFnData,
341 TQueryFilters extends QueryFilters<any> = QueryFilters,
342 >(
343 filters: TQueryFilters,
344 updater: Updater<
345 NoInfer<TQueryFnData> | undefined,
346 NoInfer<TQueryFnData> | undefined
347 >,
348 options?: SetDataOptions,
349 ): Array<[QueryKey, TQueryFnData | undefined]> {
350 return notifyManager.batch(() =>
351 this.#queryCache
352 .findAll(filters)
353 .map(({ queryKey }) => [
354 queryKey,
355 this.setQueryData<TQueryFnData>(queryKey, updater, options),
356 ]),
357 )
358 }
359​
360 /**
361 * Imperative (non-reactive) way to retrieve an existing query's state. If the query does not
362 * exist, `undefined` is returned.
363 * @param queryKey - The query key of the query to read.
364 * @returns The query's state, or `undefined` if no query with this key exists.
365 * @example
366 * ```ts
367 * const state = queryClient.getQueryState(['posts'])
368 * console.log(state?.dataUpdatedAt)
369 * ```
370 */
371 getQueryState<
372 TQueryFnData = unknown,
373 TError = DefaultError,
374 TTaggedQueryKey extends QueryKey = QueryKey,
375 TInferredQueryFnData = InferDataFromTag<TQueryFnData, TTaggedQueryKey>,
376 TInferredError = InferErrorFromTag<TError, TTaggedQueryKey>,
377 >(
378 queryKey: TTaggedQueryKey,
379 ): QueryState<TInferredQueryFnData, TInferredError> | undefined {
380 const options = this.defaultQueryOptions({ queryKey })
381 return this.#queryCache.get<TInferredQueryFnData, TInferredError>(
382 options.queryHash,
383 )?.state
384 }
385​
386 /**
387 * Removes queries from the cache that match the given filters. Unlike
388 * {@link QueryClient#invalidateQueries} or {@link QueryClient#refetchQueries}, this removes
389 * matching queries from the cache instead of refetching them. Without filters, every query in
390 * the cache is removed.
391 * @param filters - The filters that select which queries to remove. Without filters, every query
392 * is removed.
393 * @example
394 * ```ts
395 * queryClient.removeQueries({ queryKey: ['posts'], exact: true })
396 * ```
397 */
398 removeQueries<TTaggedQueryKey extends QueryKey = QueryKey>(
399 filters?: QueryFilters<TTaggedQueryKey>,
400 ): void {
401 const queryCache = this.#queryCache
402 notifyManager.batch(() => {
403 queryCache.findAll(filters).forEach((query) => {
404 queryCache.remove(query)
405 })
406 })
407 }
408​
409 /**
410 * Resets queries matching the given filters back to their initial state (e.g. any
411 * `initialData`), notifying subscribers rather than removing them. Active queries among the
412 * matched set are then refetched, and the returned promise resolves once that refetch settles.
413 * @param filters - The filters that select which queries to reset. Without filters, every query
414 * is reset.
415 * @param options - Passed to the refetch of the active matched queries, e.g. `cancelRefetch` and
416 * `throwOnError`.
417 * @returns A promise that resolves once the refetch of the active matched queries settles.
418 * @example
419 * ```ts
420 * await queryClient.resetQueries({ queryKey: ['posts'], exact: true })
421 * ```
422 */
423 resetQueries<TTaggedQueryKey extends QueryKey = QueryKey>(
424 filters?: QueryFilters<TTaggedQueryKey>,
425 options?: ResetOptions,
426 ): Promise<void> {
427 const queryCache = this.#queryCache
428​
429 return notifyManager.batch(() => {
430 const matched = queryCache.findAll(filters)
431 const queriesToRefetch = new Set(matched)
432 matched.forEach((query) => {
433 query.reset()
434 })
435 return this.refetchQueries(
436 {
437 type: 'active',
438 predicate: (query) => queriesToRefetch.has(query),
439 },
440 options,
441 )
442 })
443 }
444​
445 /**
446 * Cancels outgoing fetches for queries matching the given filters. Most useful when performing
447 * optimistic updates, since any outgoing refetch that resolves afterwards would otherwise
448 * overwrite the optimistic update. By default (`revert: true`), a cancelled query's data is
449 * reverted to its state before the outgoing fetch started.
450 *
451 * The returned promise never rejects, even if individual cancellations fail.
452 * @param filters - The filters that select which queries to cancel. Without filters, every query
453 * is cancelled.
454 * @param cancelOptions - Passed to each matched query's cancellation. `revert` defaults to
455 * `true`.
456 * @returns A promise that resolves once every cancellation has settled.
457 * @example
458 * ```ts
459 * await queryClient.cancelQueries({ queryKey: ['posts'], exact: true })
460 * ```
461 */
462 cancelQueries<TTaggedQueryKey extends QueryKey = QueryKey>(
463 filters?: QueryFilters<TTaggedQueryKey>,
464 cancelOptions: CancelOptions = {},
465 ): Promise<void> {
466 const defaultedCancelOptions = { revert: true, ...cancelOptions }
467​
468 const promises = notifyManager.batch(() =>
469 this.#queryCache
470 .findAll(filters)
471 .map((query) => query.cancel(defaultedCancelOptions)),
472 )
473​
474 return Promise.all(promises).then(noop).catch(noop)
475 }
476​
477 /**
478 * Marks queries matching the given filters as invalidated. Unlike
479 * {@link QueryClient#removeQueries}, invalidated queries stay in the cache.
480 *
481 * Unless `filters.refetchType` is `'none'`, matching queries are then refetched via
482 * {@link QueryClient#refetchQueries}, using `filters.refetchType` if set, otherwise
483 * `filters.type`, otherwise `'active'`.
484 * @param filters - The filters that select which queries to invalidate, plus `refetchType` to
485 * control which of them to refetch afterwards. Without filters, every query is invalidated.
486 * @param options - Passed to {@link QueryClient#refetchQueries}, e.g. `cancelRefetch` and
487 * `throwOnError`.
488 * @returns A promise that resolves once the refetch settles, or immediately if `refetchType` is
489 * `'none'`.
490 * @example
491 * ```ts
492 * await queryClient.invalidateQueries({ queryKey: ['posts'], refetchType: 'active' })
493 * ```
494 */
495 invalidateQueries<TTaggedQueryKey extends QueryKey = QueryKey>(
496 filters?: InvalidateQueryFilters<TTaggedQueryKey>,
497 options: InvalidateOptions = {},
498 ): Promise<void> {
499 return notifyManager.batch(() => {
500 this.#queryCache.findAll(filters).forEach((query) => {
501 query.invalidate()
502 })
503​
504 if (filters?.refetchType === 'none') {
505 return Promise.resolve()
506 }
507 return this.refetchQueries(
508 {
509 ...filters,
510 type: filters?.refetchType ?? filters?.type ?? 'active',
511 },
512 options,
513 )
514 })
515 }
516​
517 /**
518 * Refetches queries matching the given filters, regardless of whether they are stale. Without
519 * filters, every query in the cache is refetched. Queries that are disabled, or static (only
520 * have observers with a static `staleTime`), are never refetched.
521 *
522 * By default (`cancelRefetch: true`), a currently running fetch is cancelled before the new
523 * one starts. The returned promise does not reject on individual query failures unless
524 * `throwOnError` is `true`.
525 *
526 * Initially paused fetches do not delay the returned promise. Their later errors are handled
527 * even when `throwOnError` is `true`.
528 * @param filters - The filters that select which queries to refetch. Without filters, every query
529 * in the cache is included.
530 * @param options - Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling
531 * it, and `throwOnError` to `true` to reject when a refetch that was not initially paused fails.
532 * @returns A promise that resolves once all matching refetches that were not initially paused
533 * have settled.
534 * @example
535 * ```ts
536 * // refetch all active queries partially matching a query key:
537 * await queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' })
538 * ```
539 */
540 refetchQueries<TTaggedQueryKey extends QueryKey = QueryKey>(
541 filters?: RefetchQueryFilters<TTaggedQueryKey>,
542 options: RefetchOptions = {},
543 ): Promise<void> {
544 const fetchOptions = {
545 ...options,
546 cancelRefetch: options.cancelRefetch ?? true,
547 }
548 const promises = notifyManager.batch(() =>
549 this.#queryCache
550 .findAll(filters)
551 .filter((query) => !query.isDisabled() && !query.isStatic())
552 .map((query) => {
553 let promise = query.fetch(undefined, fetchOptions)
554 const isPaused = query.state.fetchStatus === 'paused'
555 if (!fetchOptions.throwOnError || isPaused) {
556 promise = promise.catch(noop)
557 }
558 return isPaused ? Promise.resolve() : promise
559 }),
560 )
561​
562 return Promise.all(promises).then(noop)
563 }
564​
565 /**
566 * Asynchronous method to fetch and cache a query, resolving with the data or throwing with
567 * the error.
568 *
569 * If the query already exists in the cache and its data is not stale (per the given
570 * `staleTime`), the cached data is returned without fetching. Otherwise, the query is fetched
571 * and the promise resolves once the fetch settles. If a `select` function is provided, it is
572 * applied to the data in both cases (cached or freshly fetched) before it is returned.
573 *
574 * Unlike a reactive observer, retries are disabled by default here (`retry: false`) unless
575 * explicitly configured, since there is no component to catch a thrown error and retry through
576 * re-render.
577 *
578 * The accepted options are `QueryObserverOptions` minus the fields that only make sense for a
579 * reactive observer β€” `enabled`, `refetchInterval`, `refetchIntervalInBackground`,
580 * `refetchOnWindowFocus`, `refetchOnReconnect`, `refetchOnMount`, `retryOnMount`,
581 * `notifyOnChangeProps`, `throwOnError`, `suspense`, and `placeholderData` are not part of this
582 * method's options.
583 *
584 * This method replaces the deprecated `fetchQuery`, and β€” combined with
585 * `{ staleTime: 'static' }` β€” the deprecated `ensureQueryData`.
586 * @param options - The query options, including the `queryKey` and the `queryFn` used if the
587 * query needs to fetch.
588 * @returns A promise that resolves to the data, or to the result of `select` if provided. It
589 * rejects with the error from the fetch or from `select`.
590 * @example
591 * ```ts
592 * try {
593 * const data = await queryClient.query({ queryKey, queryFn, staleTime: 10000 })
594 * } catch (error) {
595 * console.log(error)
596 * }
597 * ```
598 */
599 async query<
600 TQueryFnData,
601 TError = DefaultError,
602 TData = TQueryFnData,
603 TQueryData = TQueryFnData,
604 TQueryKey extends QueryKey = QueryKey,
605 TPageParam = never,
606 >(
607 options: QueryExecuteOptions<
608 TQueryFnData,
609 TError,
610 TData,
611 TQueryData,
612 TQueryKey,
613 TPageParam
614 >,
615 ): Promise<TData> {
616 const defaultedOptions = this.defaultQueryOptions(options)
617​
618 // https://github.com/tannerlinsley/react-query/issues/652
619 if (defaultedOptions.retry === undefined) {
620 defaultedOptions.retry = false
621 }
622​
623 const query = this.#queryCache.build(this, defaultedOptions)
624​
625 const isStale = query.isStaleByTime(
626 resolveQueryValue(defaultedOptions.staleTime, query),
627 )
628​
629 const queryData = isStale
630 ? await query.fetch(defaultedOptions)
631 : (query.state.data as TQueryData)
632​
633 const select = defaultedOptions.select
634​
635 if (select) {
636 return select(queryData)
637 }
638​
639 return queryData as unknown as TData
640 }
641​
642 /**
643 * Fetches and caches a query, or returns its cached data if it isn't stale. Unlike in observers,
644 * the fetch isn't retried unless `retry` is set.
645 * @param options - The query options, including the `queryKey` and the `queryFn` used if the
646 * query needs to fetch.
647 * @returns A promise that resolves to the cached or fetched data, or rejects with the fetch
648 * error.
649 * @deprecated Use queryClient.query(options) instead. This method will be removed in the next major version.
650 */
651 fetchQuery<
652 TQueryFnData,
653 TError = DefaultError,
654 TData = TQueryFnData,
655 TQueryKey extends QueryKey = QueryKey,
656 TPageParam = never,
657 >(
658 options: FetchQueryOptions<
659 TQueryFnData,
660 TError,
661 TData,
662 TQueryKey,
663 TPageParam
664 >,
665 ): Promise<TData> {
666 const defaultedOptions = this.defaultQueryOptions(options)
667​
668 // https://github.com/tannerlinsley/react-query/issues/652
669 if (defaultedOptions.retry === undefined) {
670 defaultedOptions.retry = false
671 }
672​
673 const query = this.#queryCache.build(this, defaultedOptions)
674​
675 return query.isStaleByTime(
676 resolveQueryValue(defaultedOptions.staleTime, query),
677 )
678 ? query.fetch(defaultedOptions)
679 : Promise.resolve(query.state.data as TData)
680 }
681​
682 /**
683 * Fetches and caches a query like {@link QueryClient#fetchQuery}, but ignores the result and any
684 * error.
685 * @param options - The query options, including the `queryKey` and the `queryFn` used if the
686 * query needs to fetch.
687 * @returns A promise that resolves once the fetch settles. It never rejects.
688 * @deprecated Use queryClient.query(options) instead. You can swallow errors with `.catch(noop)`. This method will be removed in the next major version.
689 */
690 prefetchQuery<
691 TQueryFnData = unknown,
692 TError = DefaultError,
693 TData = TQueryFnData,
694 TQueryKey extends QueryKey = QueryKey,
695 >(
696 options: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
697 ): Promise<void> {
698 // oxlint-disable-next-line tanstack-query/no-restricted-syntax
699 return this.fetchQuery(options).then(noop).catch(noop)
700 }
701​
702 /**
703 * Asynchronous method to fetch and cache an infinite query, resolving with an
704 * {@link InfiniteData} object or throwing with the error.
705 *
706 * Behaves like {@link QueryClient#query}, accepting the same options (minus
707 * `initialPageParam`), plus the required `initialPageParam`, and an optional `pages` /
708 * `getNextPageParam` pair used to refetch a fixed number of pages from the start.
709 *
710 * This method replaces the deprecated `fetchInfiniteQuery`, and β€” combined with
711 * `{ staleTime: 'static' }` β€” the deprecated `ensureInfiniteQueryData`.
712 * @param options - The infinite query options, including the `queryKey`, the `queryFn`, and the
713 * `initialPageParam`.
714 * @returns A promise that resolves to the {@link InfiniteData}, or to the result of `select` if
715 * provided. It rejects with the error from the fetch or from `select`.
716 * @example
717 * ```ts
718 * try {
719 * const data = await queryClient.infiniteQuery({ queryKey, queryFn, initialPageParam: 0 })
720 * console.log(data.pages)
721 * } catch (error) {
722 * console.log(error)
723 * }
724 * ```
725 */
726 infiniteQuery<
727 TQueryFnData,
728 TError = DefaultError,
729 TData = InfiniteData<TQueryFnData>,
730 TQueryKey extends QueryKey = QueryKey,
731 TPageParam = unknown,
732 >(
733 options: InfiniteQueryExecuteOptions<
734 TQueryFnData,
735 TError,
736 TData,
737 TQueryKey,
738 TPageParam
739 >,
740 ): Promise<
741 Array<TData> extends Array<InfiniteData<TQueryFnData>>
742 ? InfiniteData<TQueryFnData, TPageParam>
743 : TData
744 > {
745 options._type = 'infinite'
746 return this.query(options as any)
747 }
748​
749 /**
750 * Fetches and caches an infinite query, or returns its cached data if it isn't stale.
751 * @param options - The infinite query options, including the `queryKey`, the `queryFn`, and the
752 * `initialPageParam`.
753 * @returns A promise that resolves to the cached or fetched {@link InfiniteData}, or rejects with
754 * the fetch error.
755 * @deprecated Use queryClient.infiniteQuery(options) instead. This method will be removed in the next major version.
756 */
757 fetchInfiniteQuery<
758 TQueryFnData,
759 TError = DefaultError,
760 TData = TQueryFnData,
761 TQueryKey extends QueryKey = QueryKey,
762 TPageParam = unknown,
763 >(
764 options: FetchInfiniteQueryOptions<
765 TQueryFnData,
766 TError,
767 TData,
768 TQueryKey,
769 TPageParam
770 >,
771 ): Promise<InfiniteData<TData, TPageParam>> {
772 options._type = 'infinite'
773 // oxlint-disable-next-line tanstack-query/no-restricted-syntax
774 return this.fetchQuery(options as any)
775 }
776​
777 /**
778 * Fetches and caches an infinite query like {@link QueryClient#fetchInfiniteQuery}, but ignores
779 * the result and any error.
780 * @param options - The infinite query options, including the `queryKey`, the `queryFn`, and the
781 * `initialPageParam`.
782 * @returns A promise that resolves once the fetch settles. It never rejects.
783 * @deprecated Use queryClient.infiniteQuery(options) instead. You can swallow errors with `.catch(noop)`. This method will be removed in the next major version.
784 */
785 prefetchInfiniteQuery<
786 TQueryFnData,
787 TError = DefaultError,
788 TData = TQueryFnData,
789 TQueryKey extends QueryKey = QueryKey,
790 TPageParam = unknown,
791 >(
792 options: FetchInfiniteQueryOptions<
793 TQueryFnData,
794 TError,
795 TData,
796 TQueryKey,
797 TPageParam
798 >,
799 ): Promise<void> {
800 // oxlint-disable-next-line tanstack-query/no-restricted-syntax
801 return this.fetchInfiniteQuery(options).then(noop).catch(noop)
802 }
803​
804 /**
805 * Returns the cached data of an infinite query, or fetches it if there is none. With
806 * `revalidateIfStale`, stale cached data is also refetched in the background.
807 * @param options - The infinite query options. If the query has no cached data yet, it is fetched
808 * with these options.
809 * @returns A promise that resolves to the cached {@link InfiniteData}, or to the fetched data if
810 * nothing was cached yet.
811 * @deprecated Use queryClient.infiniteQuery({ ...options, staleTime: 'static' }) instead. This method will be removed in the next major version.
812 */
813 ensureInfiniteQueryData<
814 TQueryFnData,
815 TError = DefaultError,
816 TData = TQueryFnData,
817 TQueryKey extends QueryKey = QueryKey,
818 TPageParam = unknown,
819 >(
820 options: EnsureInfiniteQueryDataOptions<
821 TQueryFnData,
822 TError,
823 TData,
824 TQueryKey,
825 TPageParam
826 >,
827 ): Promise<InfiniteData<TData, TPageParam>> {
828 options._type = 'infinite'
829​
830 // oxlint-disable-next-line tanstack-query/no-restricted-syntax
831 return this.ensureQueryData(options as any)
832 }
833​
834 /**
835 * Resumes mutations that were paused because there was no network connection. Does nothing
836 * (resolving immediately) if the client is currently offline.
837 * @returns A promise that resolves once the resumed mutations have settled.
838 * @example
839 * ```ts
840 * import { QueryClient } from '@tanstack/query-core'
841 *
842 * const queryClient = new QueryClient()
843 * await queryClient.resumePausedMutations()
844 * ```
845 */
846 resumePausedMutations(): Promise<unknown> {
847 if (onlineManager.isOnline()) {
848 return this.#mutationCache.resumePausedMutations()
849 }
850 return Promise.resolve()
851 }
852​
853 /**
854 * Returns the query cache this client is connected to.
855 * @returns The {@link QueryCache} instance.
856 * @example
857 * ```ts
858 * import { QueryClient } from '@tanstack/query-core'
859 *
860 * const queryClient = new QueryClient()
861 * const queryCache = queryClient.getQueryCache()
862 * const queries = queryCache.findAll({ queryKey: ['posts'] })
863 * ```
864 */
865 getQueryCache(): QueryCache {
866 return this.#queryCache
867 }
868​
869 /**
870 * Returns the mutation cache this client is connected to.
871 * @returns The {@link MutationCache} instance.
872 * @example
873 * ```ts
874 * import { QueryClient } from '@tanstack/query-core'
875 *
876 * const queryClient = new QueryClient()
877 * const mutationCache = queryClient.getMutationCache()
878 * const mutations = mutationCache.findAll({ status: 'pending' })
879 * ```
880 */
881 getMutationCache(): MutationCache {
882 return this.#mutationCache
883 }
884​
885 /**
886 * Returns the default options that were set when creating the client, or via
887 * {@link QueryClient#setDefaultOptions}.
888 * @returns The client's current default options.
889 * @example
890 * ```ts
891 * import { QueryClient } from '@tanstack/query-core'
892 *
893 * const queryClient = new QueryClient()
894 * const defaultOptions = queryClient.getDefaultOptions()
895 * ```
896 */
897 getDefaultOptions(): DefaultOptions {
898 return this.#defaultOptions
899 }
900​
901 /**
902 * Dynamically sets the default options for this client, overwriting any previously defined
903 * default options.
904 * @param options - The new default options for queries and mutations.
905 * @see {@link QueryClient#getDefaultOptions}
906 * @example
907 * ```ts
908 * import { QueryClient } from '@tanstack/query-core'
909 *
910 * const queryClient = new QueryClient()
911 * queryClient.setDefaultOptions({
912 * queries: {
913 * staleTime: Infinity,
914 * },
915 * })
916 * ```
917 */
918 setDefaultOptions(options: DefaultOptions): void {
919 this.#defaultOptions = options
920 }
921​
922 /**
923 * Sets default options for queries whose query key partially matches the given `queryKey`.
924 *
925 * If several registered query defaults match a given query key, they are merged together in
926 * registration order by {@link QueryClient#getQueryDefaults}, so register defaults from the
927 * most generic key to the least generic one β€” more specific defaults should be registered
928 * after more generic ones so they take precedence.
929 * @param queryKey - The query key that query keys are partially matched against.
930 * @param options - The default options applied to matching queries.
931 * @example
932 * ```ts
933 * queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts })
934 *
935 * await queryClient.query({ queryKey: ['posts'] })
936 * ```
937 */
938 setQueryDefaults<
939 TQueryFnData = unknown,
940 TError = DefaultError,
941 TData = TQueryFnData,
942 TQueryData = TQueryFnData,
943 >(
944 queryKey: QueryKey,
945 options: Partial<
946 OmitKeyof<
947 QueryObserverOptions<TQueryFnData, TError, TData, TQueryData>,
948 'queryKey'
949 >
950 >,
951 ): void {
952 this.#queryDefaults.set(hashKey(queryKey), {
953 queryKey,
954 defaultOptions: options,
955 })
956 }
957​
958 /**
959 * Returns the default options registered for queries whose query key partially matches the
960 * given `queryKey`, via {@link QueryClient#setQueryDefaults}. If multiple registered defaults
961 * match, they are merged together in registration order.
962 * @param queryKey - The query key to look up registered defaults for.
963 * @returns The merged default options of every registration that matches, or an empty object if
964 * none match.
965 * @example
966 * ```ts
967 * const defaultOptions = queryClient.getQueryDefaults(['posts'])
968 * ```
969 */
970 getQueryDefaults(
971 queryKey: QueryKey,
972 ): OmitKeyof<QueryObserverOptions<any, any, any, any, any>, 'queryKey'> {
973 const defaults = [...this.#queryDefaults.values()]
974​
975 const result: OmitKeyof<
976 QueryObserverOptions<any, any, any, any, any>,
977 'queryKey'
978 > = {}
979​
980 defaults.forEach((queryDefault) => {
981 if (partialMatchKey(queryKey, queryDefault.queryKey)) {
982 Object.assign(result, queryDefault.defaultOptions)
983 }
984 })
985 return result
986 }
987​
988 /**
989 * Sets default options for mutations whose mutation key partially matches the given
990 * `mutationKey`. As with {@link QueryClient#setQueryDefaults}, the order of registration
991 * matters when several registered defaults match the same mutation key.
992 * @param mutationKey - The mutation key that mutation keys are partially matched against.
993 * @param options - The default options applied to matching mutations.
994 * @see {@link QueryClient#getMutationDefaults}
995 * @example
996 * ```ts
997 * queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost })
998 * ```
999 */
1000 setMutationDefaults<
1001 TData = unknown,
1002 TError = DefaultError,
1003 TVariables = void,
1004 TOnMutateResult = unknown,
1005 >(
1006 mutationKey: MutationKey,
1007 options: OmitKeyof<
1008 MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>,
1009 'mutationKey'
1010 >,
1011 ): void {
1012 this.#mutationDefaults.set(hashKey(mutationKey), {
1013 mutationKey,
1014 defaultOptions: options,
1015 })
1017​
1018 /**
1019 * Returns the default options registered for mutations whose mutation key partially matches
1020 * the given `mutationKey`, via {@link QueryClient#setMutationDefaults}. If multiple registered
1021 * defaults match, they are merged together in registration order.
1022 * @param mutationKey - The mutation key to look up registered defaults for.
1023 * @returns The merged default options of every registration that matches, or an empty object if
1024 * none match.
1025 * @example
1026 * ```ts
1027 * const defaultOptions = queryClient.getMutationDefaults(['addPost'])
1028 * ```
1029 */
1030 getMutationDefaults(
1031 mutationKey: MutationKey,
1032 ): OmitKeyof<MutationObserverOptions<any, any, any, any>, 'mutationKey'> {
1033 const defaults = [...this.#mutationDefaults.values()]
1034​
1035 const result: OmitKeyof<
1036 MutationObserverOptions<any, any, any, any>,
1037 'mutationKey'
1038 > = {}
1039​
1040 defaults.forEach((queryDefault) => {
1041 if (partialMatchKey(mutationKey, queryDefault.mutationKey)) {
1042 Object.assign(result, queryDefault.defaultOptions)
1044 })
1045​
1046 return result
1048​
1049 /**
1050 * Called by framework adapters (e.g. inside `useQuery`) to resolve the options passed by the
1051 * caller into their final, defaulted form: merging the client's own `defaultOptions.queries`,
1052 * then `queryClient.setQueryDefaults` for the given `queryKey`, then the caller's options on
1053 * top. A no-op if the options are already defaulted (`_defaulted: true`).
1054 * @param options - The query options passed by the caller.
1055 * @returns The defaulted options, with `queryHash` and dependent defaults (e.g.
1056 * `refetchOnReconnect`) filled in.
1057 */
1058 defaultQueryOptions<
1059 TQueryFnData = unknown,
1060 TError = DefaultError,
1061 TData = TQueryFnData,
1062 TQueryData = TQueryFnData,
1063 TQueryKey extends QueryKey = QueryKey,
1064 TPageParam = never,
1065 >(
1066 options:
1067 | QueryObserverOptions<
1068 TQueryFnData,
1069 TError,
1070 TData,
1071 TQueryData,
1072 TQueryKey,
1073 TPageParam
1075 | DefaultedQueryObserverOptions<
1076 TQueryFnData,
1077 TError,
1078 TData,
1079 TQueryData,
1080 TQueryKey
1081 >,
1082 ): DefaultedQueryObserverOptions<
1083 TQueryFnData,
1084 TError,
1085 TData,
1086 TQueryData,
1087 TQueryKey
1088 > {
1089 if (options._defaulted) {
1090 return options as DefaultedQueryObserverOptions<
1091 TQueryFnData,
1092 TError,
1093 TData,
1094 TQueryData,
1095 TQueryKey
1098​
1099 const defaultedOptions = {
1100 ...this.#defaultOptions.queries,
1101 ...this.getQueryDefaults(options.queryKey),
1102 ...options,
1103 _defaulted: true,
1105​
1106 if (!defaultedOptions.queryHash) {
1107 defaultedOptions.queryHash = hashQueryKeyByOptions(
1108 defaultedOptions.queryKey,
1109 defaultedOptions,
1112​
1113 // dependent default values
1114 if (defaultedOptions.refetchOnReconnect === undefined) {
1115 defaultedOptions.refetchOnReconnect =
1116 defaultedOptions.networkMode !== 'always'
1118 if (defaultedOptions.throwOnError === undefined) {
1119 defaultedOptions.throwOnError = !!defaultedOptions.suspense
1121​
1122 if (!defaultedOptions.networkMode && defaultedOptions.persister) {
1123 defaultedOptions.networkMode = 'offlineFirst'
1125​
1126 if (defaultedOptions.queryFn === skipToken) {
1127 defaultedOptions.enabled = false
1129​
1130 return defaultedOptions as DefaultedQueryObserverOptions<
1131 TQueryFnData,
1132 TError,
1133 TData,
1134 TQueryData,
1135 TQueryKey
1138​
1139 /**
1140 * The mutation counterpart of {@link QueryClient#defaultQueryOptions}. Called by framework
1141 * adapters (e.g. inside `useMutation`) to merge the client's `defaultOptions.mutations`, then
1142 * `queryClient.setMutationDefaults` for the given `mutationKey`, then the caller's options on
1143 * top. A no-op if the options are already defaulted (`_defaulted: true`).
1144 * @param options - The mutation options passed by the caller.
1145 * @returns The defaulted options.
1146 */
1147 defaultMutationOptions<T extends MutationOptions<any, any, any, any>>(
1148 options?: T,
1149 ): T {
1150 if (options?._defaulted) {
1151 return options
1153 return {
1154 ...this.#defaultOptions.mutations,
1155 ...(options?.mutationKey &&
1156 this.getMutationDefaults(options.mutationKey)),
1157 ...options,
1158 _defaulted: true,
1159 } as T
1161​
1162 /**
1163 * Clears both the query cache and the mutation cache this client is connected to.
1164 * @example
1165 * ```ts
1166 * import { QueryClient } from '@tanstack/query-core'
1168 * const queryClient = new QueryClient()
1169 * queryClient.clear()
1170 * ```
1171 */
1172 clear(): void {
1173 this.#queryCache.clear()
1174 this.#mutationCache.clear()