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

queryClient.ts

1,172 lines39.6 KB

1import {
2 functionalUpdate,
3 hashKey,
4 hashQueryKeyByOptions,
5 noop,
6 partialMatchKey,
7 resolveQueryValue,
8 skipToken,
9} from './utils'
10import { QueryCache } from './queryCache'
11import { MutationCache } from './mutationCache'
12import { focusManager } from './focusManager'
13import { onlineManager } from './onlineManager'
14import { notifyManager } from './notifyManager'
15import type {
16 CancelOptions,
17 DefaultError,
18 DefaultOptions,
19 DefaultedQueryObserverOptions,
20 EnsureInfiniteQueryDataOptions,
21 EnsureQueryDataOptions,
22 FetchInfiniteQueryOptions,
23 FetchQueryOptions,
24 InferDataFromTag,
25 InferErrorFromTag,
26 InfiniteData,
27 InfiniteQueryExecuteOptions,
28 InvalidateOptions,
29 InvalidateQueryFilters,
30 MutationKey,
31 MutationObserverOptions,
32 MutationOptions,
33 OmitKeyof,
34 QueryClientConfig,
35 QueryExecuteOptions,
36 QueryKey,
37 QueryObserverOptions,
38 QueryOptions,
39 RefetchOptions,
40 RefetchQueryFilters,
41 ResetOptions,
42 SetDataOptions,
43} from './types'
44import type { QueryState } from './query'
45import type { MutationFilters, QueryFilters, Updater } from './utils'
46​
47// TYPES
48​
49interface QueryDefaults {
50 queryKey: QueryKey
51 defaultOptions: OmitKeyof<QueryOptions<any, any, any>, 'queryKey'>
53​
54interface MutationDefaults {
55 mutationKey: MutationKey
56 defaultOptions: MutationOptions<any, any, any, any>
58​
59// CLASS
60​
61/**
62 * `QueryClient` is used to interact with a cache of queries and mutations. It owns a
63 * `QueryCache` and a `MutationCache` (creating default ones if none are passed in) and holds
64 * the default options that are applied to queries and mutations created through it.
65 * @example
66 * ```ts
67 * const queryClient = new QueryClient({
68 * defaultOptions: {
69 * queries: {
70 * staleTime: Infinity,
71 * },
72 * },
73 * })
74 *
75 * await queryClient.query({ queryKey: ['posts'], queryFn: fetchPosts })
76 * ```
77 */
78export class QueryClient {
79 #queryCache: QueryCache
80 #mutationCache: MutationCache
81 #defaultOptions: DefaultOptions
82 #queryDefaults: Map<string, QueryDefaults>
83 #mutationDefaults: Map<string, MutationDefaults>
84 #mountCount: number
85 #unsubscribeFocus?: () => void
86 #unsubscribeOnline?: () => void
87​
88 constructor(config: QueryClientConfig = {}) {
89 this.#queryCache = config.queryCache || new QueryCache()
90 this.#mutationCache = config.mutationCache || new MutationCache()
91 this.#defaultOptions = config.defaultOptions || {}
92 this.#queryDefaults = new Map()
93 this.#mutationDefaults = new Map()
94 this.#mountCount = 0
95 }
96​
97 /**
98 * Called by a framework adapter's `QueryClientProvider`-equivalent when it mounts, to start
99 * listening for focus/online events and resume paused mutations. Ref-counted via an internal
100 * mount count, so nested or multiple providers sharing the same `QueryClient` don't tear down
101 * the shared listeners until the last one unmounts.
102 */
103 mount(): void {
104 this.#mountCount++
105 if (this.#mountCount !== 1) return
106​
107 this.#unsubscribeFocus = focusManager.subscribe(async (focused) => {
108 if (focused) {
109 await this.resumePausedMutations()
110 this.#queryCache.onFocus()
111 }
112 })
113 this.#unsubscribeOnline = onlineManager.subscribe(async (online) => {
114 if (online) {
115 await this.resumePausedMutations()
116 this.#queryCache.onOnline()
117 }
118 })
119 }
120​
121 /**
122 * The inverse of {@link QueryClient#mount} β€” called by a framework adapter's
123 * `QueryClientProvider`-equivalent when it unmounts. Only tears down the focus/online
124 * listeners once the mount count returns to `0`.
125 */
126 unmount(): void {
127 this.#mountCount--
128 if (this.#mountCount !== 0) return
129​
130 this.#unsubscribeFocus?.()
131 this.#unsubscribeFocus = undefined
132​
133 this.#unsubscribeOnline?.()
134 this.#unsubscribeOnline = undefined
135 }
136​
137 /**
138 * Returns the number of queries in the cache that are currently fetching, optionally
139 * matching a set of filters. This includes background-fetching, loading new pages, and
140 * loading more infinite query results.
141 * @param filters - Narrows down which fetching queries are counted. Without filters, every
142 * fetching query is counted.
143 * @returns The number of matching queries whose `fetchStatus` is `'fetching'`.
144 * @example
145 * ```ts
146 * if (queryClient.isFetching()) {
147 * console.log('At least one query is fetching!')
148 * }
149 * ```
150 */
151 isFetching<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 * Imperative (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 // oxlint-disable-next-line tanstack-query/no-restricted-syntax
221 return this.fetchQuery(options)
222 }
223​
224 if (
225 options.revalidateIfStale &&
226 query.isStaleByTime(resolveQueryValue(defaultedOptions.staleTime, query))
227 ) {
228 // oxlint-disable-next-line tanstack-query/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 InferDataFromTag<NoInfer<TQueryFnData>, TTaggedQueryKey> | 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<
306 InferDataFromTag<NoInfer<TQueryFnData>, TTaggedQueryKey>
307 >(defaultedOptions.queryHash)
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 // oxlint-disable-next-line tanstack-query/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 // oxlint-disable-next-line tanstack-query/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 // oxlint-disable-next-line tanstack-query/no-restricted-syntax
797 return this.fetchInfiniteQuery(options).then(noop).catch(noop)
798 }
799​
800 /**
801 * Returns the cached data of an infinite query, or fetches it if there is none. With
802 * `revalidateIfStale`, stale cached data is also refetched in the background.
803 * @param options - The infinite query options. If the query has no cached data yet, it is fetched
804 * with these options.
805 * @returns A promise that resolves to the cached {@link InfiniteData}, or to the fetched data if
806 * nothing was cached yet.
807 * @deprecated Use queryClient.infiniteQuery({ ...options, staleTime: 'static' }) instead. This method will be removed in the next major version.
808 */
809 ensureInfiniteQueryData<
810 TQueryFnData,
811 TError = DefaultError,
812 TData = TQueryFnData,
813 TQueryKey extends QueryKey = QueryKey,
814 TPageParam = unknown,
815 >(
816 options: EnsureInfiniteQueryDataOptions<
817 TQueryFnData,
818 TError,
819 TData,
820 TQueryKey,
821 TPageParam
822 >,
823 ): Promise<InfiniteData<TData, TPageParam>> {
824 options._type = 'infinite'
825​
826 // oxlint-disable-next-line tanstack-query/no-restricted-syntax
827 return this.ensureQueryData(options as any)
828 }
829​
830 /**
831 * Resumes mutations that were paused because there was no network connection. Does nothing
832 * (resolving immediately) if the client is currently offline.
833 * @returns A promise that resolves once the resumed mutations have settled.
834 * @example
835 * ```ts
836 * import { QueryClient } from '@tanstack/query-core'
837 *
838 * const queryClient = new QueryClient()
839 * await queryClient.resumePausedMutations()
840 * ```
841 */
842 resumePausedMutations(): Promise<unknown> {
843 if (onlineManager.isOnline()) {
844 return this.#mutationCache.resumePausedMutations()
845 }
846 return Promise.resolve()
847 }
848​
849 /**
850 * Returns the query cache this client is connected to.
851 * @returns The {@link QueryCache} instance.
852 * @example
853 * ```ts
854 * import { QueryClient } from '@tanstack/query-core'
855 *
856 * const queryClient = new QueryClient()
857 * const queryCache = queryClient.getQueryCache()
858 * const queries = queryCache.findAll({ queryKey: ['posts'] })
859 * ```
860 */
861 getQueryCache(): QueryCache {
862 return this.#queryCache
863 }
864​
865 /**
866 * Returns the mutation cache this client is connected to.
867 * @returns The {@link MutationCache} instance.
868 * @example
869 * ```ts
870 * import { QueryClient } from '@tanstack/query-core'
871 *
872 * const queryClient = new QueryClient()
873 * const mutationCache = queryClient.getMutationCache()
874 * const mutations = mutationCache.findAll({ status: 'pending' })
875 * ```
876 */
877 getMutationCache(): MutationCache {
878 return this.#mutationCache
879 }
880​
881 /**
882 * Returns the default options that were set when creating the client, or via
883 * {@link QueryClient#setDefaultOptions}.
884 * @returns The client's current default options.
885 * @example
886 * ```ts
887 * import { QueryClient } from '@tanstack/query-core'
888 *
889 * const queryClient = new QueryClient()
890 * const defaultOptions = queryClient.getDefaultOptions()
891 * ```
892 */
893 getDefaultOptions(): DefaultOptions {
894 return this.#defaultOptions
895 }
896​
897 /**
898 * Dynamically sets the default options for this client, overwriting any previously defined
899 * default options.
900 * @param options - The new default options for queries and mutations.
901 * @see {@link QueryClient#getDefaultOptions}
902 * @example
903 * ```ts
904 * import { QueryClient } from '@tanstack/query-core'
905 *
906 * const queryClient = new QueryClient()
907 * queryClient.setDefaultOptions({
908 * queries: {
909 * staleTime: Infinity,
910 * },
911 * })
912 * ```
913 */
914 setDefaultOptions(options: DefaultOptions): void {
915 this.#defaultOptions = options
916 }
917​
918 /**
919 * Sets default options for queries whose query key partially matches the given `queryKey`.
920 *
921 * If several registered query defaults match a given query key, they are merged together in
922 * registration order by {@link QueryClient#getQueryDefaults}, so register defaults from the
923 * most generic key to the least generic one β€” more specific defaults should be registered
924 * after more generic ones so they take precedence.
925 * @param queryKey - The query key that query keys are partially matched against.
926 * @param options - The default options applied to matching queries.
927 * @example
928 * ```ts
929 * queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts })
930 *
931 * await queryClient.query({ queryKey: ['posts'] })
932 * ```
933 */
934 setQueryDefaults<
935 TQueryFnData = unknown,
936 TError = DefaultError,
937 TData = TQueryFnData,
938 TQueryData = TQueryFnData,
939 >(
940 queryKey: QueryKey,
941 options: Partial<
942 OmitKeyof<
943 QueryObserverOptions<TQueryFnData, TError, TData, TQueryData>,
944 'queryKey'
945 >
946 >,
947 ): void {
948 this.#queryDefaults.set(hashKey(queryKey), {
949 queryKey,
950 defaultOptions: options,
951 })
952 }
953​
954 /**
955 * Returns the default options registered for queries whose query key partially matches the
956 * given `queryKey`, via {@link QueryClient#setQueryDefaults}. If multiple registered defaults
957 * match, they are merged together in registration order.
958 * @param queryKey - The query key to look up registered defaults for.
959 * @returns The merged default options of every registration that matches, or an empty object if
960 * none match.
961 * @example
962 * ```ts
963 * const defaultOptions = queryClient.getQueryDefaults(['posts'])
964 * ```
965 */
966 getQueryDefaults(
967 queryKey: QueryKey,
968 ): OmitKeyof<QueryObserverOptions<any, any, any, any, any>, 'queryKey'> {
969 const defaults = [...this.#queryDefaults.values()]
970​
971 const result: OmitKeyof<
972 QueryObserverOptions<any, any, any, any, any>,
973 'queryKey'
974 > = {}
975​
976 defaults.forEach((queryDefault) => {
977 if (partialMatchKey(queryKey, queryDefault.queryKey)) {
978 Object.assign(result, queryDefault.defaultOptions)
979 }
980 })
981 return result
982 }
983​
984 /**
985 * Sets default options for mutations whose mutation key partially matches the given
986 * `mutationKey`. As with {@link QueryClient#setQueryDefaults}, the order of registration
987 * matters when several registered defaults match the same mutation key.
988 * @param mutationKey - The mutation key that mutation keys are partially matched against.
989 * @param options - The default options applied to matching mutations.
990 * @see {@link QueryClient#getMutationDefaults}
991 * @example
992 * ```ts
993 * queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost })
994 * ```
995 */
996 setMutationDefaults<
997 TData = unknown,
998 TError = DefaultError,
999 TVariables = void,
1000 TOnMutateResult = unknown,
1001 >(
1002 mutationKey: MutationKey,
1003 options: OmitKeyof<
1004 MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>,
1005 'mutationKey'
1006 >,
1007 ): void {
1008 this.#mutationDefaults.set(hashKey(mutationKey), {
1009 mutationKey,
1010 defaultOptions: options,
1011 })
1013​
1014 /**
1015 * Returns the default options registered for mutations whose mutation key partially matches
1016 * the given `mutationKey`, via {@link QueryClient#setMutationDefaults}. If multiple registered
1017 * defaults match, they are merged together in registration order.
1018 * @param mutationKey - The mutation key to look up registered defaults for.
1019 * @returns The merged default options of every registration that matches, or an empty object if
1020 * none match.
1021 * @example
1022 * ```ts
1023 * const defaultOptions = queryClient.getMutationDefaults(['addPost'])
1024 * ```
1025 */
1026 getMutationDefaults(
1027 mutationKey: MutationKey,
1028 ): OmitKeyof<MutationObserverOptions<any, any, any, any>, 'mutationKey'> {
1029 const defaults = [...this.#mutationDefaults.values()]
1030​
1031 const result: OmitKeyof<
1032 MutationObserverOptions<any, any, any, any>,
1033 'mutationKey'
1034 > = {}
1035​
1036 defaults.forEach((queryDefault) => {
1037 if (partialMatchKey(mutationKey, queryDefault.mutationKey)) {
1038 Object.assign(result, queryDefault.defaultOptions)
1040 })
1041​
1042 return result
1044​
1045 /**
1046 * Called by framework adapters (e.g. inside `useQuery`) to resolve the options passed by the
1047 * caller into their final, defaulted form: merging the client's own `defaultOptions.queries`,
1048 * then `queryClient.setQueryDefaults` for the given `queryKey`, then the caller's options on
1049 * top. A no-op if the options are already defaulted (`_defaulted: true`).
1050 * @param options - The query options passed by the caller.
1051 * @returns The defaulted options, with `queryHash` and dependent defaults (e.g.
1052 * `refetchOnReconnect`) filled in.
1053 */
1054 defaultQueryOptions<
1055 TQueryFnData = unknown,
1056 TError = DefaultError,
1057 TData = TQueryFnData,
1058 TQueryData = TQueryFnData,
1059 TQueryKey extends QueryKey = QueryKey,
1060 TPageParam = never,
1061 >(
1062 options:
1063 | QueryObserverOptions<
1064 TQueryFnData,
1065 TError,
1066 TData,
1067 TQueryData,
1068 TQueryKey,
1069 TPageParam
1071 | DefaultedQueryObserverOptions<
1072 TQueryFnData,
1073 TError,
1074 TData,
1075 TQueryData,
1076 TQueryKey
1077 >,
1078 ): DefaultedQueryObserverOptions<
1079 TQueryFnData,
1080 TError,
1081 TData,
1082 TQueryData,
1083 TQueryKey
1084 > {
1085 if (options._defaulted) {
1086 return options as DefaultedQueryObserverOptions<
1087 TQueryFnData,
1088 TError,
1089 TData,
1090 TQueryData,
1091 TQueryKey
1094​
1095 const defaultedOptions = {
1096 ...this.#defaultOptions.queries,
1097 ...this.getQueryDefaults(options.queryKey),
1098 ...options,
1099 _defaulted: true,
1101​
1102 if (!defaultedOptions.queryHash) {
1103 defaultedOptions.queryHash = hashQueryKeyByOptions(
1104 defaultedOptions.queryKey,
1105 defaultedOptions,
1108​
1109 // dependent default values
1110 if (defaultedOptions.refetchOnReconnect === undefined) {
1111 defaultedOptions.refetchOnReconnect =
1112 defaultedOptions.networkMode !== 'always'
1114 if (defaultedOptions.throwOnError === undefined) {
1115 defaultedOptions.throwOnError = !!defaultedOptions.suspense
1117​
1118 if (!defaultedOptions.networkMode && defaultedOptions.persister) {
1119 defaultedOptions.networkMode = 'offlineFirst'
1121​
1122 if (defaultedOptions.queryFn === skipToken) {
1123 defaultedOptions.enabled = false
1125​
1126 return defaultedOptions as DefaultedQueryObserverOptions<
1127 TQueryFnData,
1128 TError,
1129 TData,
1130 TQueryData,
1131 TQueryKey
1134​
1135 /**
1136 * The mutation counterpart of {@link QueryClient#defaultQueryOptions}. Called by framework
1137 * adapters (e.g. inside `useMutation`) to merge the client's `defaultOptions.mutations`, then
1138 * `queryClient.setMutationDefaults` for the given `mutationKey`, then the caller's options on
1139 * top. A no-op if the options are already defaulted (`_defaulted: true`).
1140 * @param options - The mutation options passed by the caller.
1141 * @returns The defaulted options.
1142 */
1143 defaultMutationOptions<T extends MutationOptions<any, any, any, any>>(
1144 options?: T,
1145 ): T {
1146 if (options?._defaulted) {
1147 return options
1149 return {
1150 ...this.#defaultOptions.mutations,
1151 ...(options?.mutationKey &&
1152 this.getMutationDefaults(options.mutationKey)),
1153 ...options,
1154 _defaulted: true,
1155 } as T
1157​
1158 /**
1159 * Clears both the query cache and the mutation cache this client is connected to.
1160 * @example
1161 * ```ts
1162 * import { QueryClient } from '@tanstack/query-core'
1164 * const queryClient = new QueryClient()
1165 * queryClient.clear()
1166 * ```
1167 */
1168 clear(): void {
1169 this.#queryCache.clear()
1170 this.#mutationCache.clear()