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

queryClient.ts

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