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