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.#client = config.client
184 this.#cache = this.#client.getQueryCache()
185 this.#defaultOptions = config.defaultOptions
186 this.setOptions(config.options)
187 this.observers = []
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, this.#client.isServer)
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 isServer: this.#client.isServer,
543 canRun: () => true,
544 })
545β
546 try {
547 const data = await this.#retryer.start()
548 // this is more of a runtime guard
549 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
550 if (data === undefined) {
551 if (process.env.NODE_ENV !== 'production') {
552 console.error(
553 `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,
554 )
555 }
556 throw new Error(`${this.queryHash} data is undefined`)
557 }
558β
559 this.setData(data)
560β
561 // Notify cache callback
562 this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)
563 this.#cache.config.onSettled?.(
564 data,
565 this.state.error as any,
566 this as Query<any, any, any, any>,
567 )
568 return data
569 } catch (error) {
570 if (error instanceof CancelledError) {
571 if (error.silent) {
572 // silent cancellation implies a new fetch is going to be started,
573 // so we piggyback onto that promise
574 return this.#retryer.promise
575 } else if (error.revert) {
576 // transform error into reverted state data
577 // if the initial fetch was cancelled, we have no data, so we have
578 // to get reject with a CancelledError
579 if (this.state.data === undefined) {
580 throw error
581 }
582 return this.state.data
583 }
584 }
585 this.#dispatch({
586 type: 'error',
587 error: error as TError,
588 })
589β
590 // Notify cache callback
591 this.#cache.config.onError?.(
592 error as any,
593 this as Query<any, any, any, any>,
594 )
595 this.#cache.config.onSettled?.(
596 this.state.data,
597 error as any,
598 this as Query<any, any, any, any>,
599 )
600β
601 throw error // rethrow the error for further handling
602 } finally {
603 // Schedule query gc after fetching
604 this.scheduleGc()
605 }
606 }
607β
608 #dispatch(action: Action<TData, TError>): void {
609 const reducer = (
610 state: QueryState<TData, TError>,
611 ): QueryState<TData, TError> => {
612 switch (action.type) {
613 case 'failed':
614 return {
615 ...state,
616 fetchFailureCount: action.failureCount,
617 fetchFailureReason: action.error,
618 }
619 case 'pause':
620 return {
621 ...state,
622 fetchStatus: 'paused',
623 }
624 case 'continue':
625 return {
626 ...state,
627 fetchStatus: 'fetching',
628 }
629 case 'fetch':
630 return {
631 ...state,
632 ...fetchState(state.data, this.options),
633 fetchMeta: action.meta ?? null,
634 }
635 case 'success':
636 const newState = {
637 ...state,
638 ...successState(action.data, action.dataUpdatedAt),
639 dataUpdateCount: state.dataUpdateCount + 1,
640 ...(!action.manual && {
641 fetchStatus: 'idle' as const,
642 fetchFailureCount: 0,
643 fetchFailureReason: null,
644 }),
645 }
646 // If fetching ends successfully, we don't need revertState as a fallback anymore.
647 // For manual updates, capture the state to revert to it in case of a cancellation.
648 this.#revertState = action.manual ? newState : undefined
649β
650 return newState
651 case 'error':
652 const error = action.error
653 return {
654 ...state,
655 error,
656 errorUpdateCount: state.errorUpdateCount + 1,
657 errorUpdatedAt: Date.now(),
658 fetchFailureCount: state.fetchFailureCount + 1,
659 fetchFailureReason: error,
660 fetchStatus: 'idle',
661 status: 'error',
662 // flag existing data as invalidated if we get a background error
663 // note that "no data" always means stale so we can set unconditionally here
664 isInvalidated: true,
665 }
666 case 'invalidate':
667 return {
668 ...state,
669 isInvalidated: true,
670 }
671 case 'setState':
672 return {
673 ...state,
674 ...action.state,
675 }
676 }
677 }
678β
679 this.state = reducer(this.state)
680β
681 notifyManager.batch(() => {
682 this.observers.forEach((observer) => {
683 observer.onQueryUpdate()
684 })
685β
686 this.#cache.notify({ query: this, type: 'updated', action })
687 })
688 }
689}
690β
691export function fetchState<
692 TQueryFnData,
693 TError,
694 TData,
695 TQueryKey extends QueryKey,
696>(
697 data: TData | undefined,
698 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
699) {
700 return {
701 fetchFailureCount: 0,
702 fetchFailureReason: null,
703 fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',
704 ...(data === undefined &&
705 ({
706 error: null,
707 status: 'pending',
708 } as const)),
709 } as const
710}
711β
712function successState<TData>(data: TData | undefined, dataUpdatedAt?: number) {
713 return {
714 data,
715 dataUpdatedAt: dataUpdatedAt ?? Date.now(),
716 error: null,
717 isInvalidated: false,
718 status: 'success' as const,
719 }
720}
721β
722function getDefaultState<
723 TQueryFnData,
724 TError,
725 TData,
726 TQueryKey extends QueryKey,
727>(
728 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
729): QueryState<TData, TError> {
730 const data =
731 typeof options.initialData === 'function'
732 ? (options.initialData as InitialDataFunction<TData>)()
733 : options.initialData
734β
735 const hasData = data !== undefined
736β
737 const initialDataUpdatedAt = hasData
738 ? typeof options.initialDataUpdatedAt === 'function'
739 ? options.initialDataUpdatedAt()
740 : options.initialDataUpdatedAt
741 : 0
742β
743 return {
744 data,
745 dataUpdateCount: 0,
746 dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,
747 error: null,
748 errorUpdateCount: 0,
749 errorUpdatedAt: 0,
750 fetchFailureCount: 0,
751 fetchFailureReason: null,
752 fetchMeta: null,
753 isInvalidated: false,
754 status: hasData ? 'success' : 'pending',
755 fetchStatus: 'idle',
756 }
757}