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