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

queryClient.ts

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