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

queryClient.ts

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