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