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

queryClient.ts

1,190 lines40.0 KB

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