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>
729 | undefined,
730 fn: context.fetchFn as () => Promise<TData>,
731 onCancel: (error) => {
732 if (error instanceof CancelledError && error.revert) {
733 this.setState({
734 ...this.#revertState,
735 fetchStatus: 'idle' as const,
736 })
737 }
738 abortController.abort()
739 },
740 onFail: (failureCount, error) => {
741 this.#dispatch({ type: 'failed', failureCount, error })
742 },
743 onPause: () => {
744 this.#dispatch({ type: 'pause' })
745 },
746 onContinue: () => {
747 this.#dispatch({ type: 'continue' })
748 },
749 retry: context.options.retry,
750 retryDelay: context.options.retryDelay,
751 networkMode: context.options.networkMode,
752 canRun: () => true,
753 }))
754
755 try {
756 const data = await retryer.start()
757 // this is more of a runtime guard
758 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
759 if (data === undefined) {
760 if (process.env.NODE_ENV !== 'production') {
761 console.error(
762 `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,
763 )
764 }
765 throw new Error(`${this.queryHash} data is undefined`)
766 }
767
768 this.setData(data)
769
770 // Notify cache callback
771 this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)
772 this.#cache.config.onSettled?.(
773 data,
774 this.state.error as any,
775 this as Query<any, any, any, any>,
776 )
777 return data
778 } catch (error) {
779 if (error instanceof CancelledError) {
780 if (error.silent) {
781 // silent cancellation implies a new fetch is going to be started,
782 // so we piggyback onto that promise
783 return this.#retryer.promise
784 } else if (error.revert) {
785 // transform error into reverted state data
786 // if the initial fetch was cancelled, we have no data, so we have
787 // to get reject with a CancelledError
788 if (this.state.data === undefined) {
789 throw error
790 }
791 return this.state.data
792 }
793 }
794 this.#dispatch({
795 type: 'error',
796 error: error as TError,
797 })
798
799 // Notify cache callback
800 this.#cache.config.onError?.(
801 error as any,
802 this as Query<any, any, any, any>,
803 )
804 this.#cache.config.onSettled?.(
805 this.state.data,
806 error as any,
807 this as Query<any, any, any, any>,
808 )
809
810 throw error // rethrow the error for further handling
811 } finally {
812 // The settled retryer's promise would otherwise pin this fetch's raw
813 // result (a second copy after structural sharing) for the query's lifetime
814 if (this.#retryer === retryer) {
815 this.#retryer = undefined
816 }
817 // Schedule query gc after fetching
818 this.scheduleGc()
819 }
820 }
821
822 #dispatch(action: Action<TData, TError>): void {
823 const reducer = (
824 state: QueryState<TData, TError>,
825 ): QueryState<TData, TError> => {
826 switch (action.type) {
827 case 'failed':
828 return {
829 ...state,
830 fetchFailureCount: action.failureCount,
831 fetchFailureReason: action.error,
832 }
833 case 'pause':
834 return {
835 ...state,
836 fetchStatus: 'paused',
837 }
838 case 'continue':
839 return {
840 ...state,
841 fetchStatus: 'fetching',
842 }
843 case 'fetch':
844 return {
845 ...state,
846 ...fetchState(state.data, this.options),
847 fetchMeta: action.meta ?? null,
848 }
849 case 'success':
850 const newState = {
851 ...state,
852 ...successState(action.data, action.dataUpdatedAt),
853 dataUpdateCount: state.dataUpdateCount + 1,
854 ...(!action.manual && {
855 fetchStatus: 'idle' as const,
856 fetchFailureCount: 0,
857 fetchFailureReason: null,
858 }),
859 }
860 // If fetching ends successfully, we don't need revertState as a fallback anymore.
861 // For manual updates, capture the state to revert to it in case of a cancellation.
862 this.#revertState = action.manual ? newState : undefined
863
864 return newState
865 case 'error':
866 const error = action.error
867 return {
868 ...state,
869 error,
870 errorUpdateCount: state.errorUpdateCount + 1,
871 errorUpdatedAt: Date.now(),
872 fetchFailureCount: state.fetchFailureCount + 1,
873 fetchFailureReason: error,
874 fetchStatus: 'idle',
875 status: 'error',
876 // flag existing data as invalidated if we get a background error
877 // note that "no data" always means stale so we can set unconditionally here
878 isInvalidated: true,
879 }
880 case 'invalidate':
881 return {
882 ...state,
883 isInvalidated: true,
884 }
885 case 'setState':
886 return {
887 ...state,
888 ...action.state,
889 }
890 }
891 }
892
893 this.state = reducer(this.state)
894
895 notifyManager.batch(() => {
896 // Keep the current iteration stable if an observer unsubscribes
897 // synchronously while it is being notified.
898 this.observers.slice().forEach((observer) => {
899 observer.onQueryUpdate()
900 })
901
902 this.#cache.notify({ query: this, type: 'updated', action })
903 })
904 }
905}
906
907export function fetchState<
908 TQueryFnData,
909 TError,
910 TData,
911 TQueryKey extends QueryKey,
912>(
913 data: TData | undefined,
914 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
915) {
916 return {
917 fetchFailureCount: 0,
918 fetchFailureReason: null,
919 fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',
920 ...(data === undefined &&
921 ({
922 error: null,
923 status: 'pending',
924 } as const)),
925 } as const
926}
927
928function successState<TData>(data: TData | undefined, dataUpdatedAt?: number) {
929 return {
930 data,
931 dataUpdatedAt: dataUpdatedAt ?? Date.now(),
932 error: null,
933 isInvalidated: false,
934 status: 'success' as const,
935 }
936}
937
938function getDefaultState<
939 TQueryFnData,
940 TError,
941 TData,
942 TQueryKey extends QueryKey,
943>(
944 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
945): QueryState<TData, TError> {
946 const data =
947 typeof options.initialData === 'function'
948 ? (options.initialData as InitialDataFunction<TData>)()
949 : options.initialData
950
951 const hasData = data !== undefined
952
953 const initialDataUpdatedAt = hasData
954 ? typeof options.initialDataUpdatedAt === 'function'
955 ? options.initialDataUpdatedAt()
956 : options.initialDataUpdatedAt
957 : 0
958
959 return {
960 data,
961 dataUpdateCount: 0,
962 dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,
963 error: null,
964 errorUpdateCount: 0,
965 errorUpdatedAt: 0,
966 fetchFailureCount: 0,
967 fetchFailureReason: null,
968 fetchMeta: null,
969 isInvalidated: false,
970 status: hasData ? 'success' : 'pending',
971 fetchStatus: 'idle',
972 }
973}