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

query.ts

1,145 lines32.9 KB

1import {
2 ensureQueryFn,
3 noop,
4 replaceData,
5 resolveQueryValue,
6 skipToken,
7 timeUntilStale,
8} from './utils'
9import { notifyManager } from './notifyManager'
10import { CancelledError, canFetch, createRetryer } from './retryer'
11import { Removable } from './removable'
12import { infiniteQueryBehavior } from './infiniteQueryBehavior'
13import type { QueryCache } from './queryCache'
14import type { QueryClient } from './queryClient'
15import type {
16 CancelOptions,
17 DefaultError,
18 FetchStatus,
19 InitialDataFunction,
20 OmitKeyof,
21 QueryFunctionContext,
22 QueryKey,
23 QueryMeta,
24 QueryOptions,
25 QueryStatus,
26 SetDataOptions,
27 StaleTime,
28} from './types'
29import type { QueryObserver } from './queryObserver'
30import type { Retryer } from './retryer'
31​
32// TYPES
33​
34interface QueryConfig<
35 TQueryFnData,
36 TError,
37 TData,
38 TQueryKey extends QueryKey = QueryKey,
39> {
40 client: QueryClient
41 queryKey: TQueryKey
42 queryHash: string
43 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
44 defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
45 state?: QueryState<TData, TError>
47​
48/**
49 * The raw state stored on a `Query` instance. This is the underlying state that
50 * observer results (e.g. `QueryObserverResult`) are derived from.
51 */
52export interface QueryState<TData = unknown, TError = DefaultError> {
53 /** The last successfully resolved data for the query. */
54 data: TData | undefined
55 /** The number of times the query has successfully resolved. */
56 dataUpdateCount: number
57 /**
58 * The timestamp for when the query most recently returned the `status` as
59 * `"success"`.
60 */
61 dataUpdatedAt: number
62 /**
63 * The error object for the query, if the last attempt resulted in an error.
64 *
65 * - Defaults to `null`.
66 */
67 error: TError | null
68 /**
69 * The sum of all errors, incremented every time the query resolves with an
70 * error.
71 */
72 errorUpdateCount: number
73 /**
74 * The timestamp for when the query most recently returned the `status` as
75 * `"error"`.
76 */
77 errorUpdatedAt: number
78 /**
79 * The failure count for the current fetch.
80 *
81 * - Incremented every time the fetch fails.
82 * - Reset to `0` when the fetch succeeds.
83 */
84 fetchFailureCount: number
85 /**
86 * The reason the current fetch failed, as reported by the retryer.
87 *
88 * - Reset to `null` when the fetch succeeds.
89 */
90 fetchFailureReason: TError | null
91 /**
92 * Metadata passed to the currently in-flight (or most recent) fetch, e.g. the
93 * `fetchMore` direction for infinite queries.
94 */
95 fetchMeta: FetchMeta | null
96 /**
97 * Whether the query has been marked as invalidated via `invalidate()`.
98 *
99 * - Reset to `false` whenever the query resolves successfully.
100 */
101 isInvalidated: boolean
102 /**
103 * The status of the query.
104 *
105 * - `pending` if there's no cached data and no attempt was finished yet.
106 * - `error` if the last attempt resulted in an error.
107 * - `success` if the query has data.
108 */
109 status: QueryStatus
110 /**
111 * The fetch status of the query.
112 *
113 * - `fetching`: the `queryFn` is currently executing.
114 * - `paused`: a fetch wanted to run but has been paused (see network mode).
115 * - `idle`: the query is not fetching.
116 */
117 fetchStatus: FetchStatus
119​
120/**
121 * The context passed to a {@link QueryBehavior}'s `onFetch`, which can replace
122 * `fetchFn` to change how the query fetches (e.g. to fetch pages for an
123 * infinite query).
124 */
125export interface FetchContext<
126 TQueryFnData,
127 TError,
128 TData,
129 TQueryKey extends QueryKey = QueryKey,
130> {
131 /**
132 * The function that runs the fetch. By default it calls `queryFn`; `onFetch`
133 * can replace it.
134 */
135 fetchFn: () => unknown | Promise<unknown>
136 /** The options of this fetch. */
137 fetchOptions?: FetchOptions
138 /** The `AbortSignal` that aborts when the fetch is cancelled. */
139 signal: AbortSignal
140 /** The options of the query. */
141 options: QueryOptions<TQueryFnData, TError, TData, any>
142 /** The `QueryClient` the query belongs to. */
143 client: QueryClient
144 /** The key of the query. */
145 queryKey: TQueryKey
146 /** The state of the query when the fetch starts. */
147 state: QueryState<TData, TError>
149​
150/**
151 * Customizes how a query fetches, e.g. the behavior that fetches the pages of
152 * an infinite query.
153 */
154export interface QueryBehavior<
155 TQueryFnData = unknown,
156 TError = DefaultError,
157 TData = TQueryFnData,
158 TQueryKey extends QueryKey = QueryKey,
159> {
160 /**
161 * Called before each fetch of the query, e.g. to replace `fetchFn` in the
162 * context.
163 */
164 onFetch: (
165 context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,
166 query: Query,
167 ) => void
169​
170/**
171 * The direction an infinite query fetches in: `'forward'` for the next page,
172 * `'backward'` for the previous one.
173 */
174export type FetchDirection = 'forward' | 'backward'
175​
176/**
177 * Metadata for a fetch, e.g. the direction when an infinite query fetches more
178 * pages.
179 */
180export interface FetchMeta {
181 /**
182 * Set when an infinite query fetches another page, with the direction to
183 * fetch in.
184 */
185 fetchMore?: { direction: FetchDirection }
187​
188/** Options for a single fetch of a query. */
189export interface FetchOptions<TData = unknown> {
190 /**
191 * If `true`, an in-flight fetch is cancelled before starting a new one, when
192 * the query already has data. Otherwise, the in-flight fetch is reused.
193 */
194 cancelRefetch?: boolean
195 /** Metadata of the fetch, stored in the query's `fetchMeta` state. */
196 meta?: FetchMeta
197 /**
198 * A promise to use for the first attempt instead of calling `fetchFn`, e.g. a
199 * pending promise restored by `hydrate`.
200 */
201 initialPromise?: Promise<TData>
203​
204interface FailedAction<TError> {
205 type: 'failed'
206 failureCount: number
207 error: TError
209​
210interface FetchAction {
211 type: 'fetch'
212 meta?: FetchMeta
214​
215interface SuccessAction<TData> {
216 data: TData | undefined
217 type: 'success'
218 dataUpdatedAt?: number
219 manual?: boolean
221​
222interface ErrorAction<TError> {
223 type: 'error'
224 error: TError
226​
227interface InvalidateAction {
228 type: 'invalidate'
230​
231interface PauseAction {
232 type: 'pause'
234​
235interface ContinueAction {
236 type: 'continue'
238​
239interface SetStateAction<TData, TError> {
240 type: 'setState'
241 state: Partial<QueryState<TData, TError>>
243​
244/**
245 * The actions a query dispatches to update its state, e.g. when it starts
246 * fetching, fails, or succeeds.
247 */
248export type Action<TData, TError> =
249 | ContinueAction
250 | ErrorAction<TError>
251 | FailedAction<TError>
252 | FetchAction
253 | InvalidateAction
254 | PauseAction
255 | SetStateAction<TData, TError>
256 | SuccessAction<TData>
257​
258// CLASS
259​
260/**
261 * Represents a single cached query. A `Query` holds the query's key, options,
262 * state (data/error/status), and the observers currently subscribed to it.
263 *
264 * Instances are created and managed internally by `QueryCache`; application
265 * code typically interacts with queries indirectly through `QueryClient` or a
266 * framework hook like `useQuery`. Direct access to a `Query` instance is
267 * possible via `queryCache.find()`/`findAll()` for inspecting cache state.
268 *
269 * @example
270 * ;```ts
271 * const queryCache = queryClient.getQueryCache()
272 * const query = queryCache.find({ queryKey: ['posts'] })
273 *
274 * if (query) {
275 * console.log(query.state.dataUpdatedAt)
276 * }
277 * ```
278 */
279export class Query<
280 TQueryFnData = unknown,
281 TError = DefaultError,
282 TData = TQueryFnData,
283 TQueryKey extends QueryKey = QueryKey,
284> extends Removable {
285 queryKey: TQueryKey
286 queryHash: string
287 options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
288 state: QueryState<TData, TError>
289 #queryType?: 'infinite'
290​
291 #initialState: QueryState<TData, TError>
292 #revertState?: QueryState<TData, TError>
293 #cache: QueryCache
294 #client: QueryClient
295 #retryer?: Retryer<TData>
296 observers: Array<QueryObserver<any, any, any, any, any>>
297 #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
298 #abortSignalConsumed: boolean
299​
300 constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {
301 super()
302​
303 this.#abortSignalConsumed = false
304 this.#defaultOptions = config.defaultOptions
305 this.setOptions(config.options)
306 this.observers = []
307 this.#client = config.client
308 this.#cache = this.#client.getQueryCache()
309 this.queryKey = config.queryKey
310 this.queryHash = config.queryHash
311 this.#initialState = getDefaultState(this.options)
312 this.state = config.state ?? this.#initialState
313 this.scheduleGc()
314 }
315 /**
316 * The `meta` object passed in the query's options, if any.
317 *
318 * @returns The query's `meta`, or `undefined` if none was set.
319 */
320 get meta(): QueryMeta | undefined {
321 return this.options.meta
322 }
323​
324 /**
325 * `'infinite'` for an infinite query, otherwise `undefined`.
326 *
327 * @returns The type of the query, set from the `_type` option (e.g.
328 * `'infinite'`).
329 * @internal
330 */
331 get queryType() {
332 return this.#queryType
333 }
334​
335 /**
336 * The promise for the currently in-flight fetch, if the query is fetching.
337 * `undefined` when the query is not fetching.
338 *
339 * @returns The promise of the in-flight fetch, or `undefined`.
340 */
341 get promise(): Promise<TData> | undefined {
342 return this.#retryer?.promise
343 }
344​
345 /**
346 * Replaces the query's options and applies their `gcTime`. If the query has
347 * no data yet, it gets the `initialData` from the new options, if any.
348 *
349 * @param options - The new query options, merged on top of the query's
350 * default options.
351 * @internal
352 */
353 setOptions(
354 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
355 ): void {
356 this.options = { ...this.#defaultOptions, ...options }
357​
358 if (options?._type) {
359 this.#queryType = options._type
360 }
361​
362 this.updateGcTime(this.options.gcTime)
363​
364 // oxlint-disable-next-line typescript/no-unnecessary-condition
365 if (this.state && this.state.data === undefined) {
366 const defaultState = getDefaultState(this.options)
367 if (defaultState.data !== undefined) {
368 this.setState(
369 successState(defaultState.data, defaultState.dataUpdatedAt),
370 )
371 this.#initialState = defaultState
372 }
373 }
374 }
375​
376 protected override optionalRemove() {
377 if (!this.observers.length && this.state.fetchStatus === 'idle') {
378 this.#cache.remove(this)
379 }
380 }
381​
382 /**
383 * Writes new data to the query and marks it as successfully fetched.
384 *
385 * @param newData - The data to write. Structural sharing with the current
386 * data is applied.
387 * @param options - Set `updatedAt` to override the timestamp, and `manual` to
388 * mark the write as manual (e.g. from `queryClient.setQueryData`).
389 * @returns The data that was written.
390 * @internal
391 */
392 setData(
393 newData: TData,
394 options?: SetDataOptions & { manual: boolean },
395 ): TData {
396 const data = replaceData(this.state.data, newData, this.options)
397​
398 // Set data and mark it as cached
399 this.#dispatch({
400 data,
401 type: 'success',
402 dataUpdatedAt: options?.updatedAt,
403 manual: options?.manual,
404 })
405​
406 return data
407 }
408​
409 /**
410 * Merges the given partial state directly into this query's state, notifying
411 * observers. Used by persistence and broadcast plugins to restore a state
412 * snapshot, and by devtools to let a user manually trigger a loading/error
413 * state or edit the cached data.
414 *
415 * @param state - The partial state to merge into the query's state.
416 */
417 setState(state: Partial<QueryState<TData, TError>>): void {
418 this.#dispatch({ type: 'setState', state })
419 }
420​
421 /**
422 * Cancels the query's currently in-flight fetch, if any.
423 *
424 * - Returns a promise that resolves once the cancellation has settled.
425 * - If no fetch is in progress, resolves immediately.
426 *
427 * @example
428 * ;```ts
429 * await query.cancel()
430 * ```
431 *
432 * @param options - Set `revert` to restore the state from before the fetch
433 * started, and `silent` to suppress the cancellation error when a new fetch
434 * replaces the cancelled one.
435 * @returns A promise that resolves once the cancellation has settled.
436 */
437 cancel(options?: CancelOptions): Promise<void> {
438 const promise = this.#retryer?.promise
439 this.#retryer?.cancel(options)
440 return promise ? promise.then(noop).catch(noop) : Promise.resolve()
441 }
442​
443 /**
444 * Clears the query's garbage collection timeout and silently cancels any
445 * in-flight fetch. Called by `QueryCache` when the query is removed from the
446 * cache.
447 *
448 * @see {@link Query#cancel}
449 */
450 override destroy(): void {
451 super.destroy()
452​
453 this.cancel({ silent: true })
454 }
455​
456 /**
457 * The state the query was created with.
458 *
459 * @returns The state the query had when it was first created, used by
460 * {@link Query#reset}.
461 * @internal
462 */
463 get resetState(): QueryState<TData, TError> {
464 return this.#initialState
465 }
466​
467 /**
468 * Resets the query back to its initial state (the state it had when it was
469 * first created, e.g. any `initialData`), destroying it first to cancel any
470 * in-flight fetch.
471 */
472 reset(): void {
473 this.destroy()
474 this.setState(this.resetState)
475 }
476​
477 /**
478 * Returns `true` if the query has at least one observer for which `enabled`
479 * does not resolve to `false`.
480 *
481 * @returns `true` if the query has an enabled observer.
482 */
483 isActive(): boolean {
484 return this.observers.some(
485 (observer) => resolveQueryValue(observer.options.enabled, this) !== false,
486 )
487 }
488​
489 /**
490 * Returns `true` if the query is disabled, meaning it will not fetch
491 * automatically.
492 *
493 * - If the query has observers, it is disabled when none of them are active
494 * (see `isActive`).
495 * - If the query has no observers, it is disabled when its `queryFn` is
496 * `skipToken` or it has never been fetched.
497 *
498 * @returns `true` if the query is disabled.
499 */
500 isDisabled(): boolean {
501 if (this.getObserversCount() > 0) {
502 return !this.isActive()
503 }
504 // if a query has no observers, it should still be considered disabled if it never attempted a fetch
505 return this.options.queryFn === skipToken || !this.isFetched()
506 }
507​
508 /**
509 * Returns `true` if the query has been fetched, i.e. it has resolved with
510 * either data or an error at least once.
511 *
512 * @returns `true` if the query has been fetched.
513 */
514 isFetched() {
515 return this.state.dataUpdateCount + this.state.errorUpdateCount > 0
516 }
517​
518 /**
519 * Returns `true` if the query has at least one observer configured with
520 * `staleTime: 'static'`, meaning it is treated as never stale.
521 *
522 * @returns `true` if the query is static.
523 */
524 isStatic(): boolean {
525 if (this.getObserversCount() > 0) {
526 return this.observers.some(
527 (observer) =>
528 resolveQueryValue(observer.options.staleTime, this) === 'static',
529 )
530 }
531​
532 return false
533 }
534​
535 /**
536 * Returns `true` if the query is stale.
537 *
538 * - If the query has observers, defers to whether any observer's current result
539 * reports `isStale` (which accounts for each observer's own `staleTime` and
540 * `enabled` state).
541 * - If the query has no observers, it is considered stale when it has no data
542 * or has been invalidated.
543 *
544 * @example
545 * ;```ts
546 * if (query.isStale()) {
547 * // refetch or otherwise treat the cached data as outdated
548 * }
549 * ```
550 *
551 * @returns `true` if the query is stale.
552 * @see {@link Query#isStaleByTime}
553 */
554 isStale(): boolean {
555 // check observers first, their `isStale` has the source of truth
556 // calculated with `isStaleByTime` and it takes `enabled` into account
557 if (this.getObserversCount() > 0) {
558 return this.observers.some(
559 (observer) => observer.getCurrentResult().isStale,
560 )
561 }
562​
563 return this.state.data === undefined || this.state.isInvalidated
564 }
565​
566 /**
567 * Returns `true` if the query's data is stale relative to the given
568 * `staleTime` (defaults to `0`).
569 *
570 * - A query with no data is always stale.
571 * - `staleTime: 'static'` is never stale.
572 * - An invalidated query is always stale.
573 * - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`.
574 *
575 * @example
576 * ;```ts
577 * const isStale = query.isStaleByTime(1000 * 60)
578 * ```
579 *
580 * @param staleTime - The time, in milliseconds, after which data is
581 * considered stale, or `'static'` to never treat existing data as stale. A
582 * query without data is stale either way.
583 * @returns `true` if the query's data is stale.
584 * @see {@link Query#isStale}
585 */
586 isStaleByTime(staleTime: StaleTime = 0): boolean {
587 // no data is always stale
588 if (this.state.data === undefined) {
589 return true
590 }
591 // static is never stale
592 if (staleTime === 'static') {
593 return false
594 }
595 // if the query is invalidated, it is stale
596 if (this.state.isInvalidated) {
597 return true
598 }
599​
600 return !timeUntilStale(this.state.dataUpdatedAt, staleTime)
601 }
602​
603 /**
604 * Refetches the query when the window regains focus, if an observer wants
605 * that, and continues a paused fetch.
606 *
607 * @internal
608 */
609 onFocus(): void {
610 const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())
611​
612 observer?.refetch({ cancelRefetch: false })
613​
614 // Continue fetch if currently paused
615 this.#retryer?.continue()
616 }
617​
618 /**
619 * Refetches the query when the app reconnects, if an observer wants that, and
620 * continues a paused fetch.
621 *
622 * @internal
623 */
624 onOnline(): void {
625 const observer = this.observers.find((x) => x.shouldFetchOnReconnect())
626​
627 observer?.refetch({ cancelRefetch: false })
628​
629 // Continue fetch if currently paused
630 this.#retryer?.continue()
631 }
632​
633 /**
634 * Subscribes an observer to the query and stops its garbage collection.
635 *
636 * @param observer - The observer to add. Adding an observer that is already
637 * subscribed does nothing.
638 * @internal
639 */
640 addObserver(observer: QueryObserver<any, any, any, any, any>): void {
641 if (!this.observers.includes(observer)) {
642 this.observers.push(observer)
643​
644 // Stop the query from being garbage collected
645 this.clearGcTimeout()
646​
647 this.#cache.notify({ type: 'observerAdded', query: this, observer })
648 }
649 }
650​
651 /**
652 * Unsubscribes an observer from the query.
653 *
654 * @param observer - The observer to remove. When the last observer is
655 * removed, the in-flight fetch is cancelled if its abort signal was
656 * consumed (otherwise only its retries are stopped), and garbage collection
657 * is scheduled.
658 * @internal
659 */
660 removeObserver(observer: QueryObserver<any, any, any, any, any>): void {
661 const index = this.observers.indexOf(observer)
662 if (index !== -1) {
663 this.observers.splice(index, 1)
664​
665 if (!this.observers.length) {
666 // If the transport layer does not support cancellation
667 // we'll let the query continue so the result can be cached
668 if (this.#retryer) {
669 if (
670 this.#abortSignalConsumed ||
671 (this.state.fetchStatus === 'paused' &&
672 this.state.status === 'pending')
673 ) {
674 this.#retryer.cancel({ revert: true })
675 } else {
676 this.#retryer.cancelRetry()
677 }
678 }
679​
680 this.scheduleGc()
681 }
682​
683 this.#cache.notify({ type: 'observerRemoved', query: this, observer })
684 }
685 }
686​
687 /**
688 * Returns the number of observers currently subscribed to this query.
689 *
690 * @example
691 * ;```ts
692 * if (query.getObserversCount() === 0) {
693 * // no component is currently watching this query
694 * }
695 * ```
696 *
697 * @returns The number of observers.
698 */
699 getObserversCount(): number {
700 return this.observers.length
701 }
702​
703 /**
704 * Marks the query as invalidated, unless it is already invalidated. This
705 * updates `state.isInvalidated` and notifies observers, but does not by
706 * itself trigger a refetch.
707 *
708 * @example
709 * ;```ts
710 * query.invalidate()
711 * ```
712 */
713 invalidate(): void {
714 if (!this.state.isInvalidated) {
715 this.#dispatch({ type: 'invalidate' })
716 }
717 }
718​
719 /**
720 * Fetches the query, i.e. runs its `queryFn` (through any configured
721 * retryer/behavior) and updates the query's state with the result.
722 *
723 * - If a fetch is already in flight, returns its promise instead of starting a
724 * new one, unless `fetchOptions.cancelRefetch` is set and the query already
725 * has data, in which case the current fetch is silently cancelled first.
726 * - If `options` is passed, it replaces the query's current options before
727 * fetching.
728 *
729 * @param options - Query options that replace the query's current options
730 * before fetching. They are not applied when an in-flight fetch is reused.
731 * @param fetchOptions - Set `cancelRefetch` to cancel an in-flight fetch
732 * first (only if the query already has data), and `meta` to pass extra
733 * information to the query's behavior.
734 * @returns A promise that resolves with the fetched data, or rejects with the
735 * fetch error. If the fetch is cancelled with `revert` while the query has
736 * data, it resolves with the restored data instead.
737 */
738 async fetch(
739 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
740 fetchOptions?: FetchOptions<TQueryFnData>,
741 ): Promise<TData> {
742 if (
743 this.state.fetchStatus !== 'idle' &&
744 // If the promise in the retryer is already rejected, we have to definitely
745 // re-start the fetch; there is a chance that the query is still in a
746 // pending state when that happens
747 this.#retryer?.status() !== 'rejected'
748 ) {
749 if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {
750 // Silently cancel current fetch if the user wants to cancel refetch
751 this.cancel({ silent: true })
752 } else if (this.#retryer) {
753 // make sure that retries that were potentially cancelled due to unmounts can continue
754 this.#retryer.continueRetry()
755 // Return current promise if we are already fetching
756 return this.#retryer.promise
757 }
758 }
759​
760 // Update config if passed, otherwise the config from the last execution is used
761 if (options) {
762 this.setOptions(options)
763 }
764​
765 // Use the options from the first observer with a query function if no function is found.
766 // This can happen when the query is hydrated or created with setQueryData.
767 if (!this.options.queryFn) {
768 const observer = this.observers.find((x) => x.options.queryFn)
769 if (observer) {
770 this.setOptions(observer.options)
771 }
772 }
773​
774 if (process.env.NODE_ENV !== 'production') {
775 if (!Array.isArray(this.options.queryKey)) {
776 console.error(
777 `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`,
778 )
779 }
780 }
781​
782 const abortController = new AbortController()
783​
784 // Adds an enumerable signal property to the object that
785 // which sets abortSignalConsumed to true when the signal
786 // is read.
787 const addSignalProperty = (object: unknown) => {
788 Object.defineProperty(object, 'signal', {
789 enumerable: true,
790 get: () => {
791 this.#abortSignalConsumed = true
792 return abortController.signal
793 },
794 })
795 }
796​
797 // Create fetch function
798 const fetchFn = () => {
799 const queryFn = ensureQueryFn(this.options, fetchOptions)
800​
801 // Create query function context
802 const createQueryFnContext = (): QueryFunctionContext<TQueryKey> => {
803 const queryFnContext: OmitKeyof<
804 QueryFunctionContext<TQueryKey>,
805 'signal'
806 > = {
807 client: this.#client,
808 queryKey: this.queryKey,
809 meta: this.meta,
810 }
811 addSignalProperty(queryFnContext)
812 return queryFnContext as QueryFunctionContext<TQueryKey>
813 }
814​
815 const queryFnContext = createQueryFnContext()
816​
817 this.#abortSignalConsumed = false
818 if (this.options.persister) {
819 return this.options.persister(
820 queryFn,
821 queryFnContext,
822 this as unknown as Query,
823 )
824 }
825​
826 return queryFn(queryFnContext)
827 }
828​
829 // Trigger behavior hook
830 const createFetchContext = (): FetchContext<
831 TQueryFnData,
832 TError,
833 TData,
834 TQueryKey
835 > => {
836 const context: OmitKeyof<
837 FetchContext<TQueryFnData, TError, TData, TQueryKey>,
838 'signal'
839 > = {
840 fetchOptions,
841 options: this.options,
842 queryKey: this.queryKey,
843 client: this.#client,
844 state: this.state,
845 fetchFn,
846 }
847​
848 addSignalProperty(context)
849 return context as FetchContext<TQueryFnData, TError, TData, TQueryKey>
850 }
851​
852 const context = createFetchContext()
853​
854 const behavior =
855 this.#queryType === 'infinite'
856 ? (infiniteQueryBehavior(
857 (this.options as { pages?: number }).pages,
858 ) as QueryBehavior<TQueryFnData, TError, TData, TQueryKey>)
859 : this.options.behavior
860 behavior?.onFetch(context, this as unknown as Query)
861​
862 // Store state in case the current fetch needs to be reverted
863 this.#revertState = this.state
864​
865 // Set to fetching state if not already in it
866 if (
867 this.state.fetchStatus === 'idle' ||
868 this.state.fetchMeta !== context.fetchOptions?.meta
869 ) {
870 this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })
871 }
872​
873 // Try to fetch the data
874 const retryer = (this.#retryer = createRetryer({
875 initialPromise: fetchOptions?.initialPromise as
876 | Promise<TData>
877 | undefined,
878 fn: context.fetchFn as () => Promise<TData>,
879 onCancel: (error) => {
880 if (error instanceof CancelledError && error.revert) {
881 this.setState({
882 ...this.#revertState,
883 fetchStatus: 'idle' as const,
884 })
885 }
886 abortController.abort()
887 },
888 onFail: (failureCount, error) => {
889 this.#dispatch({ type: 'failed', failureCount, error })
890 },
891 onPause: () => {
892 this.#dispatch({ type: 'pause' })
893 },
894 onContinue: () => {
895 this.#dispatch({ type: 'continue' })
896 },
897 retry: context.options.retry,
898 retryDelay: context.options.retryDelay,
899 networkMode: context.options.networkMode,
900 canRun: () => true,
901 }))
902​
903 try {
904 const data = await retryer.start()
905 // this is more of a runtime guard
906 if (data === undefined) {
907 if (process.env.NODE_ENV !== 'production') {
908 console.error(
909 `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,
910 )
911 }
912 throw new Error(`${this.queryHash} data is undefined`)
913 }
914​
915 this.setData(data)
916​
917 // Notify cache callback
918 this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)
919 this.#cache.config.onSettled?.(
920 data,
921 this.state.error as any,
922 this as Query<any, any, any, any>,
923 )
924 return data
925 } catch (error) {
926 if (error instanceof CancelledError) {
927 if (error.silent) {
928 // silent cancellation implies a new fetch is going to be started,
929 // so we piggyback onto that promise
930 return this.#retryer.promise
931 } else if (error.revert) {
932 // transform error into reverted state data
933 // if the initial fetch was cancelled, we have no data, so we have
934 // to get reject with a CancelledError
935 if (this.state.data === undefined) {
936 throw error
937 }
938 return this.state.data
939 }
940 }
941 this.#dispatch({
942 type: 'error',
943 error: error as TError,
944 })
945​
946 // Notify cache callback
947 this.#cache.config.onError?.(
948 error as any,
949 this as Query<any, any, any, any>,
950 )
951 this.#cache.config.onSettled?.(
952 this.state.data,
953 error as any,
954 this as Query<any, any, any, any>,
955 )
956​
957 throw error // rethrow the error for further handling
958 } finally {
959 // The settled retryer's promise would otherwise pin this fetch's raw
960 // result (a second copy after structural sharing) for the query's lifetime
961 if (this.#retryer === retryer) {
962 this.#retryer = undefined
963 }
964 // Schedule query gc after fetching
965 this.scheduleGc()
966 }
967 }
968​
969 #dispatch(action: Action<TData, TError>): void {
970 const reducer = (
971 state: QueryState<TData, TError>,
972 ): QueryState<TData, TError> => {
973 switch (action.type) {
974 case 'failed':
975 return {
976 ...state,
977 fetchFailureCount: action.failureCount,
978 fetchFailureReason: action.error,
979 }
980 case 'pause':
981 return {
982 ...state,
983 fetchStatus: 'paused',
984 }
985 case 'continue':
986 return {
987 ...state,
988 fetchStatus: 'fetching',
989 }
990 case 'fetch':
991 return {
992 ...state,
993 ...fetchState(state.data, this.options),
994 fetchMeta: action.meta ?? null,
995 }
996 case 'success':
997 const newState = {
998 ...state,
999 ...successState(action.data, action.dataUpdatedAt),
1000 dataUpdateCount: state.dataUpdateCount + 1,
1001 ...(!action.manual && {
1002 fetchStatus: 'idle' as const,
1003 fetchFailureCount: 0,
1004 fetchFailureReason: null,
1005 }),
1007 // If fetching ends successfully, we don't need revertState as a fallback anymore.
1008 // For manual updates, capture the state to revert to it in case of a cancellation.
1009 this.#revertState = action.manual ? newState : undefined
1010​
1011 return newState
1012 case 'error':
1013 const error = action.error
1014 return {
1015 ...state,
1016 error,
1017 errorUpdateCount: state.errorUpdateCount + 1,
1018 errorUpdatedAt: Date.now(),
1019 fetchFailureCount: state.fetchFailureCount + 1,
1020 fetchFailureReason: error,
1021 fetchStatus: 'idle',
1022 status: 'error',
1023 // flag existing data as invalidated if we get a background error
1024 // note that "no data" always means stale so we can set unconditionally here
1025 isInvalidated: true,
1027 case 'invalidate':
1028 return {
1029 ...state,
1030 isInvalidated: true,
1032 case 'setState':
1033 return {
1034 ...state,
1035 ...action.state,
1039​
1040 this.state = reducer(this.state)
1041​
1042 notifyManager.batch(() => {
1043 // Keep the current iteration stable if an observer unsubscribes
1044 // synchronously while it is being notified.
1045 this.observers.slice().forEach((observer) => {
1046 observer.onQueryUpdate()
1047 })
1048​
1049 this.#cache.notify({ query: this, type: 'updated', action })
1050 })
1053​
1054/**
1055 * Returns the state changes applied when a query starts fetching.
1057 * @param data - The query's current data. If it is `undefined`, the query is
1058 * also reset to `'pending'` with no error.
1059 * @param options - The query options, whose `networkMode` decides whether the
1060 * query is `'fetching'` or `'paused'`.
1061 * @returns The partial query state for a starting fetch.
1062 */
1063export function fetchState<
1064 TQueryFnData,
1065 TError,
1066 TData,
1067 TQueryKey extends QueryKey,
1069 data: TData | undefined,
1070 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
1071) {
1072 return {
1073 fetchFailureCount: 0,
1074 fetchFailureReason: null,
1075 fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',
1076 ...(data === undefined &&
1077 ({
1078 error: null,
1079 status: 'pending',
1080 } as const)),
1081 } as const
1083​
1084/**
1085 * Returns the state changes applied when a query receives data.
1087 * @param data - The new data.
1088 * @param dataUpdatedAt - The timestamp the data is recorded with. Defaults to
1089 * the current time.
1090 * @returns The partial query state for a successful update.
1091 */
1092function successState<TData>(data: TData | undefined, dataUpdatedAt?: number) {
1093 return {
1094 data,
1095 dataUpdatedAt: dataUpdatedAt ?? Date.now(),
1096 error: null,
1097 isInvalidated: false,
1098 status: 'success' as const,
1101​
1102/**
1103 * Returns the initial state of a query, based on its `initialData` and
1104 * `initialDataUpdatedAt` options.
1106 * @param options - The query options.
1107 * @returns The initial query state: `'success'` if `initialData` is set,
1108 * otherwise `'pending'`.
1109 */
1110function getDefaultState<
1111 TQueryFnData,
1112 TError,
1113 TData,
1114 TQueryKey extends QueryKey,
1116 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
1117): QueryState<TData, TError> {
1118 const data =
1119 typeof options.initialData === 'function'
1120 ? (options.initialData as InitialDataFunction<TData>)()
1121 : options.initialData
1122​
1123 const hasData = data !== undefined
1124​
1125 const initialDataUpdatedAt = hasData
1126 ? typeof options.initialDataUpdatedAt === 'function'
1127 ? options.initialDataUpdatedAt()
1128 : options.initialDataUpdatedAt
1129 : 0
1130​
1131 return {
1132 data,
1133 dataUpdateCount: 0,
1134 dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,
1135 error: null,
1136 errorUpdateCount: 0,
1137 errorUpdatedAt: 0,
1138 fetchFailureCount: 0,
1139 fetchFailureReason: null,
1140 fetchMeta: null,
1141 isInvalidated: false,
1142 status: hasData ? 'success' : 'pending',
1143 fetchStatus: 'idle',