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

query.ts

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