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

queryClient.ts

1,177 lines39.8 KB

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