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