Open History to see the last commit
1import {
2 ensureQueryFn,
3 noop,
4 replaceData,
5 resolveEnabled,
6 resolveStaleTime,
7 skipToken,
8 timeUntilStale,
9} from './utils'
10import { notifyManager } from './notifyManager'
11import { CancelledError, canFetch, createRetryer } from './retryer'
12import { Removable } from './removable'
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β
48export interface QueryState<TData = unknown, TError = DefaultError> {
49 data: TData | undefined
50 dataUpdateCount: number
51 dataUpdatedAt: number
52 error: TError | null
53 errorUpdateCount: number
54 errorUpdatedAt: number
55 fetchFailureCount: number
56 fetchFailureReason: TError | null
57 fetchMeta: FetchMeta | null
58 isInvalidated: boolean
59 status: QueryStatus
60 fetchStatus: FetchStatus
61}
62β
63export interface FetchContext<
64 TQueryFnData,
65 TError,
66 TData,
67 TQueryKey extends QueryKey = QueryKey,
68> {
69 fetchFn: () => unknown | Promise<unknown>
70 fetchOptions?: FetchOptions
71 signal: AbortSignal
72 options: QueryOptions<TQueryFnData, TError, TData, any>
73 client: QueryClient
74 queryKey: TQueryKey
75 state: QueryState<TData, TError>
76}
77β
78export interface QueryBehavior<
79 TQueryFnData = unknown,
80 TError = DefaultError,
81 TData = TQueryFnData,
82 TQueryKey extends QueryKey = QueryKey,
83> {
84 onFetch: (
85 context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,
86 query: Query,
87 ) => void
88}
89β
90export type FetchDirection = 'forward' | 'backward'
91β
92export interface FetchMeta {
93 fetchMore?: { direction: FetchDirection }
94}
95β
96export interface FetchOptions<TData = unknown> {
97 cancelRefetch?: boolean
98 meta?: FetchMeta
99 initialPromise?: Promise<TData>
100}
101β
102interface FailedAction<TError> {
103 type: 'failed'
104 failureCount: number
105 error: TError
106}
107β
108interface FetchAction {
109 type: 'fetch'
110 meta?: FetchMeta
111}
112β
113interface SuccessAction<TData> {
114 data: TData | undefined
115 type: 'success'
116 dataUpdatedAt?: number
117 manual?: boolean
118}
119β
120interface ErrorAction<TError> {
121 type: 'error'
122 error: TError
123}
124β
125interface InvalidateAction {
126 type: 'invalidate'
127}
128β
129interface PauseAction {
130 type: 'pause'
131}
132β
133interface ContinueAction {
134 type: 'continue'
135}
136β
137interface SetStateAction<TData, TError> {
138 type: 'setState'
139 state: Partial<QueryState<TData, TError>>
140 setStateOptions?: SetStateOptions
141}
142β
143export type Action<TData, TError> =
144 | ContinueAction
145 | ErrorAction<TError>
146 | FailedAction<TError>
147 | FetchAction
148 | InvalidateAction
149 | PauseAction
150 | SetStateAction<TData, TError>
151 | SuccessAction<TData>
152β
153export interface SetStateOptions {
154 meta?: any
155}
156β
157// CLASS
158β
159export class Query<
160 TQueryFnData = unknown,
161 TError = DefaultError,
162 TData = TQueryFnData,
163 TQueryKey extends QueryKey = QueryKey,
164> extends Removable {
165 queryKey: TQueryKey
166 queryHash: string
167 options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
168 state: QueryState<TData, TError>
169β
170 #initialState: QueryState<TData, TError>
171 #revertState?: QueryState<TData, TError>
172 #cache: QueryCache
173 #client: QueryClient
174 #retryer?: Retryer<TData>
175 observers: Array<QueryObserver<any, any, any, any, any>>
176 #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
177 #abortSignalConsumed: boolean
178β
179 constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {
180 super()
181β
182 this.#abortSignalConsumed = false
183 this.#defaultOptions = config.defaultOptions
184 this.setOptions(config.options)
185 this.observers = []
186 this.#client = config.client
187 this.#cache = this.#client.getQueryCache()
188 this.queryKey = config.queryKey
189 this.queryHash = config.queryHash
190 this.#initialState = getDefaultState(this.options)
191 this.state = config.state ?? this.#initialState
192 this.scheduleGc()
193 }
194 get meta(): QueryMeta | undefined {
195 return this.options.meta
196 }
197β
198 get promise(): Promise<TData> | undefined {
199 return this.#retryer?.promise
200 }
201β
202 setOptions(
203 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
204 ): void {
205 this.options = { ...this.#defaultOptions, ...options }
206β
207 this.updateGcTime(this.options.gcTime)
208β
209 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
210 if (this.state && this.state.data === undefined) {
211 const defaultState = getDefaultState(this.options)
212 if (defaultState.data !== undefined) {
213 this.setState(
214 successState(defaultState.data, defaultState.dataUpdatedAt),
215 )
216 this.#initialState = defaultState
217 }
218 }
219 }
220β
221 protected optionalRemove() {
222 if (!this.observers.length && this.state.fetchStatus === 'idle') {
223 this.#cache.remove(this)
224 }
225 }
226β
227 setData(
228 newData: TData,
229 options?: SetDataOptions & { manual: boolean },
230 ): TData {
231 const data = replaceData(this.state.data, newData, this.options)
232β
233 // Set data and mark it as cached
234 this.#dispatch({
235 data,
236 type: 'success',
237 dataUpdatedAt: options?.updatedAt,
238 manual: options?.manual,
239 })
240β
241 return data
242 }
243β
244 setState(
245 state: Partial<QueryState<TData, TError>>,
246 setStateOptions?: SetStateOptions,
247 ): void {
248 this.#dispatch({ type: 'setState', state, setStateOptions })
249 }
250β
251 cancel(options?: CancelOptions): Promise<void> {
252 const promise = this.#retryer?.promise
253 this.#retryer?.cancel(options)
254 return promise ? promise.then(noop).catch(noop) : Promise.resolve()
255 }
256β
257 destroy(): void {
258 super.destroy()
259β
260 this.cancel({ silent: true })
261 }
262β
263 reset(): void {
264 this.destroy()
265 this.setState(this.#initialState)
266 }
267β
268 isActive(): boolean {
269 return this.observers.some(
270 (observer) => resolveEnabled(observer.options.enabled, this) !== false,
271 )
272 }
273β
274 isDisabled(): boolean {
275 if (this.getObserversCount() > 0) {
276 return !this.isActive()
277 }
278 // if a query has no observers, it should still be considered disabled if it never attempted a fetch
279 return (
280 this.options.queryFn === skipToken ||
281 this.state.dataUpdateCount + this.state.errorUpdateCount === 0
282 )
283 }
284β
285 isStatic(): boolean {
286 if (this.getObserversCount() > 0) {
287 return this.observers.some(
288 (observer) =>
289 resolveStaleTime(observer.options.staleTime, this) === 'static',
290 )
291 }
292β
293 return false
294 }
295β
296 isStale(): boolean {
297 // check observers first, their `isStale` has the source of truth
298 // calculated with `isStaleByTime` and it takes `enabled` into account
299 if (this.getObserversCount() > 0) {
300 return this.observers.some(
301 (observer) => observer.getCurrentResult().isStale,
302 )
303 }
304β
305 return this.state.data === undefined || this.state.isInvalidated
306 }
307β
308 isStaleByTime(staleTime: StaleTime = 0): boolean {
309 // no data is always stale
310 if (this.state.data === undefined) {
311 return true
312 }
313 // static is never stale
314 if (staleTime === 'static') {
315 return false
316 }
317 // if the query is invalidated, it is stale
318 if (this.state.isInvalidated) {
319 return true
320 }
321β
322 return !timeUntilStale(this.state.dataUpdatedAt, staleTime)
323 }
324β
325 onFocus(): void {
326 const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())
327β
328 observer?.refetch({ cancelRefetch: false })
329β
330 // Continue fetch if currently paused
331 this.#retryer?.continue()
332 }
333β
334 onOnline(): void {
335 const observer = this.observers.find((x) => x.shouldFetchOnReconnect())
336β
337 observer?.refetch({ cancelRefetch: false })
338β
339 // Continue fetch if currently paused
340 this.#retryer?.continue()
341 }
342β
343 addObserver(observer: QueryObserver<any, any, any, any, any>): void {
344 if (!this.observers.includes(observer)) {
345 this.observers.push(observer)
346β
347 // Stop the query from being garbage collected
348 this.clearGcTimeout()
349β
350 this.#cache.notify({ type: 'observerAdded', query: this, observer })
351 }
352 }
353β
354 removeObserver(observer: QueryObserver<any, any, any, any, any>): void {
355 if (this.observers.includes(observer)) {
356 this.observers = this.observers.filter((x) => x !== observer)
357β
358 if (!this.observers.length) {
359 // If the transport layer does not support cancellation
360 // we'll let the query continue so the result can be cached
361 if (this.#retryer) {
362 if (this.#abortSignalConsumed) {
363 this.#retryer.cancel({ revert: true })
364 } else {
365 this.#retryer.cancelRetry()
366 }
367 }
368β
369 this.scheduleGc()
370 }
371β
372 this.#cache.notify({ type: 'observerRemoved', query: this, observer })
373 }
374 }
375β
376 getObserversCount(): number {
377 return this.observers.length
378 }
379β
380 invalidate(): void {
381 if (!this.state.isInvalidated) {
382 this.#dispatch({ type: 'invalidate' })
383 }
384 }
385β
386 async fetch(
387 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
388 fetchOptions?: FetchOptions<TQueryFnData>,
389 ): Promise<TData> {
390 if (
391 this.state.fetchStatus !== 'idle' &&
392 // If the promise in the retryer is already rejected, we have to definitely
393 // re-start the fetch; there is a chance that the query is still in a
394 // pending state when that happens
395 this.#retryer?.status() !== 'rejected'
396 ) {
397 if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {
398 // Silently cancel current fetch if the user wants to cancel refetch
399 this.cancel({ silent: true })
400 } else if (this.#retryer) {
401 // make sure that retries that were potentially cancelled due to unmounts can continue
402 this.#retryer.continueRetry()
403 // Return current promise if we are already fetching
404 return this.#retryer.promise
405 }
406 }
407β
408 // Update config if passed, otherwise the config from the last execution is used
409 if (options) {
410 this.setOptions(options)
411 }
412β
413 // Use the options from the first observer with a query function if no function is found.
414 // This can happen when the query is hydrated or created with setQueryData.
415 if (!this.options.queryFn) {
416 const observer = this.observers.find((x) => x.options.queryFn)
417 if (observer) {
418 this.setOptions(observer.options)
419 }
420 }
421β
422 if (process.env.NODE_ENV !== 'production') {
423 if (!Array.isArray(this.options.queryKey)) {
424 console.error(
425 `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']`,
426 )
427 }
428 }
429β
430 const abortController = new AbortController()
431β
432 // Adds an enumerable signal property to the object that
433 // which sets abortSignalConsumed to true when the signal
434 // is read.
435 const addSignalProperty = (object: unknown) => {
436 Object.defineProperty(object, 'signal', {
437 enumerable: true,
438 get: () => {
439 this.#abortSignalConsumed = true
440 return abortController.signal
441 },
442 })
443 }
444β
445 // Create fetch function
446 const fetchFn = () => {
447 const queryFn = ensureQueryFn(this.options, fetchOptions)
448β
449 // Create query function context
450 const createQueryFnContext = (): QueryFunctionContext<TQueryKey> => {
451 const queryFnContext: OmitKeyof<
452 QueryFunctionContext<TQueryKey>,
453 'signal'
454 > = {
455 client: this.#client,
456 queryKey: this.queryKey,
457 meta: this.meta,
458 }
459 addSignalProperty(queryFnContext)
460 return queryFnContext as QueryFunctionContext<TQueryKey>
461 }
462β
463 const queryFnContext = createQueryFnContext()
464β
465 this.#abortSignalConsumed = false
466 if (this.options.persister) {
467 return this.options.persister(
468 queryFn,
469 queryFnContext,
470 this as unknown as Query,
471 )
472 }
473β
474 return queryFn(queryFnContext)
475 }
476β
477 // Trigger behavior hook
478 const createFetchContext = (): FetchContext<
479 TQueryFnData,
480 TError,
481 TData,
482 TQueryKey
483 > => {
484 const context: OmitKeyof<
485 FetchContext<TQueryFnData, TError, TData, TQueryKey>,
486 'signal'
487 > = {
488 fetchOptions,
489 options: this.options,
490 queryKey: this.queryKey,
491 client: this.#client,
492 state: this.state,
493 fetchFn,
494 }
495β
496 addSignalProperty(context)
497 return context as FetchContext<TQueryFnData, TError, TData, TQueryKey>
498 }
499β
500 const context = createFetchContext()
501β
502 this.options.behavior?.onFetch(context, this as unknown as Query)
503β
504 // Store state in case the current fetch needs to be reverted
505 this.#revertState = this.state
506β
507 // Set to fetching state if not already in it
508 if (
509 this.state.fetchStatus === 'idle' ||
510 this.state.fetchMeta !== context.fetchOptions?.meta
511 ) {
512 this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })
513 }
514β
515 // Try to fetch the data
516 this.#retryer = createRetryer({
517 initialPromise: fetchOptions?.initialPromise as
518 | Promise<TData>
519 | undefined,
520 fn: context.fetchFn as () => Promise<TData>,
521 onCancel: (error) => {
522 if (error instanceof CancelledError && error.revert) {
523 this.setState({
524 ...this.#revertState,
525 fetchStatus: 'idle' as const,
526 })
527 }
528 abortController.abort()
529 },
530 onFail: (failureCount, error) => {
531 this.#dispatch({ type: 'failed', failureCount, error })
532 },
533 onPause: () => {
534 this.#dispatch({ type: 'pause' })
535 },
536 onContinue: () => {
537 this.#dispatch({ type: 'continue' })
538 },
539 retry: context.options.retry,
540 retryDelay: context.options.retryDelay,
541 networkMode: context.options.networkMode,
542 canRun: () => true,
543 })
544β
545 try {
546 const data = await this.#retryer.start()
547 // this is more of a runtime guard
548 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
549 if (data === undefined) {
550 if (process.env.NODE_ENV !== 'production') {
551 console.error(
552 `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,
553 )
554 }
555 throw new Error(`${this.queryHash} data is undefined`)
556 }
557β
558 this.setData(data)
559β
560 // Notify cache callback
561 this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)
562 this.#cache.config.onSettled?.(
563 data,
564 this.state.error as any,
565 this as Query<any, any, any, any>,
566 )
567 return data
568 } catch (error) {
569 if (error instanceof CancelledError) {
570 if (error.silent) {
571 // silent cancellation implies a new fetch is going to be started,
572 // so we piggyback onto that promise
573 return this.#retryer.promise
574 } else if (error.revert) {
575 // transform error into reverted state data
576 // if the initial fetch was cancelled, we have no data, so we have
577 // to get reject with a CancelledError
578 if (this.state.data === undefined) {
579 throw error
580 }
581 return this.state.data
582 }
583 }
584 this.#dispatch({
585 type: 'error',
586 error: error as TError,
587 })
588β
589 // Notify cache callback
590 this.#cache.config.onError?.(
591 error as any,
592 this as Query<any, any, any, any>,
593 )
594 this.#cache.config.onSettled?.(
595 this.state.data,
596 error as any,
597 this as Query<any, any, any, any>,
598 )
599β
600 throw error // rethrow the error for further handling
601 } finally {
602 // Schedule query gc after fetching
603 this.scheduleGc()
604 }
605 }
606β
607 #dispatch(action: Action<TData, TError>): void {
608 const reducer = (
609 state: QueryState<TData, TError>,
610 ): QueryState<TData, TError> => {
611 switch (action.type) {
612 case 'failed':
613 return {
614 ...state,
615 fetchFailureCount: action.failureCount,
616 fetchFailureReason: action.error,
617 }
618 case 'pause':
619 return {
620 ...state,
621 fetchStatus: 'paused',
622 }
623 case 'continue':
624 return {
625 ...state,
626 fetchStatus: 'fetching',
627 }
628 case 'fetch':
629 return {
630 ...state,
631 ...fetchState(state.data, this.options),
632 fetchMeta: action.meta ?? null,
633 }
634 case 'success':
635 const newState = {
636 ...state,
637 ...successState(action.data, action.dataUpdatedAt),
638 dataUpdateCount: state.dataUpdateCount + 1,
639 ...(!action.manual && {
640 fetchStatus: 'idle' as const,
641 fetchFailureCount: 0,
642 fetchFailureReason: null,
643 }),
644 }
645 // If fetching ends successfully, we don't need revertState as a fallback anymore.
646 // For manual updates, capture the state to revert to it in case of a cancellation.
647 this.#revertState = action.manual ? newState : undefined
648β
649 return newState
650 case 'error':
651 const error = action.error
652 return {
653 ...state,
654 error,
655 errorUpdateCount: state.errorUpdateCount + 1,
656 errorUpdatedAt: Date.now(),
657 fetchFailureCount: state.fetchFailureCount + 1,
658 fetchFailureReason: error,
659 fetchStatus: 'idle',
660 status: 'error',
661 // flag existing data as invalidated if we get a background error
662 // note that "no data" always means stale so we can set unconditionally here
663 isInvalidated: true,
664 }
665 case 'invalidate':
666 return {
667 ...state,
668 isInvalidated: true,
669 }
670 case 'setState':
671 return {
672 ...state,
673 ...action.state,
674 }
675 }
676 }
677β
678 this.state = reducer(this.state)
679β
680 notifyManager.batch(() => {
681 this.observers.forEach((observer) => {
682 observer.onQueryUpdate()
683 })
684β
685 this.#cache.notify({ query: this, type: 'updated', action })
686 })
687 }
688}
689β
690export function fetchState<
691 TQueryFnData,
692 TError,
693 TData,
694 TQueryKey extends QueryKey,
695>(
696 data: TData | undefined,
697 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
698) {
699 return {
700 fetchFailureCount: 0,
701 fetchFailureReason: null,
702 fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',
703 ...(data === undefined &&
704 ({
705 error: null,
706 status: 'pending',
707 } as const)),
708 } as const
709}
710β
711function successState<TData>(data: TData | undefined, dataUpdatedAt?: number) {
712 return {
713 data,
714 dataUpdatedAt: dataUpdatedAt ?? Date.now(),
715 error: null,
716 isInvalidated: false,
717 status: 'success' as const,
718 }
719}
720β
721function getDefaultState<
722 TQueryFnData,
723 TError,
724 TData,
725 TQueryKey extends QueryKey,
726>(
727 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
728): QueryState<TData, TError> {
729 const data =
730 typeof options.initialData === 'function'
731 ? (options.initialData as InitialDataFunction<TData>)()
732 : options.initialData
733β
734 const hasData = data !== undefined
735β
736 const initialDataUpdatedAt = hasData
737 ? typeof options.initialDataUpdatedAt === 'function'
738 ? options.initialDataUpdatedAt()
739 : options.initialDataUpdatedAt
740 : 0
741β
742 return {
743 data,
744 dataUpdateCount: 0,
745 dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,
746 error: null,
747 errorUpdateCount: 0,
748 errorUpdatedAt: 0,
749 fetchFailureCount: 0,
750 fetchFailureReason: null,
751 fetchMeta: null,
752 isInvalidated: false,
753 status: hasData ? 'success' : 'pending',
754 fetchStatus: 'idle',
755 }
756}