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