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.setData(defaultState.data, {
214 updatedAt: defaultState.dataUpdatedAt,
215 manual: true,
216 })
217 this.#initialState = defaultState
218 }
219 }
220 }
221β
222 protected optionalRemove() {
223 if (!this.observers.length && this.state.fetchStatus === 'idle') {
224 this.#cache.remove(this)
225 }
226 }
227β
228 setData(
229 newData: TData,
230 options?: SetDataOptions & { manual: boolean },
231 ): TData {
232 const data = replaceData(this.state.data, newData, this.options)
233β
234 // Set data and mark it as cached
235 this.#dispatch({
236 data,
237 type: 'success',
238 dataUpdatedAt: options?.updatedAt,
239 manual: options?.manual,
240 })
241β
242 return data
243 }
244β
245 setState(
246 state: Partial<QueryState<TData, TError>>,
247 setStateOptions?: SetStateOptions,
248 ): void {
249 this.#dispatch({ type: 'setState', state, setStateOptions })
250 }
251β
252 cancel(options?: CancelOptions): Promise<void> {
253 const promise = this.#retryer?.promise
254 this.#retryer?.cancel(options)
255 return promise ? promise.then(noop).catch(noop) : Promise.resolve()
256 }
257β
258 destroy(): void {
259 super.destroy()
260β
261 this.cancel({ silent: true })
262 }
263β
264 reset(): void {
265 this.destroy()
266 this.setState(this.#initialState)
267 }
268β
269 isActive(): boolean {
270 return this.observers.some(
271 (observer) => resolveEnabled(observer.options.enabled, this) !== false,
272 )
273 }
274β
275 isDisabled(): boolean {
276 if (this.getObserversCount() > 0) {
277 return !this.isActive()
278 }
279 // if a query has no observers, it should still be considered disabled if it never attempted a fetch
280 return (
281 this.options.queryFn === skipToken ||
282 this.state.dataUpdateCount + this.state.errorUpdateCount === 0
283 )
284 }
285β
286 isStatic(): boolean {
287 if (this.getObserversCount() > 0) {
288 return this.observers.some(
289 (observer) =>
290 resolveStaleTime(observer.options.staleTime, this) === 'static',
291 )
292 }
293β
294 return false
295 }
296β
297 isStale(): boolean {
298 // check observers first, their `isStale` has the source of truth
299 // calculated with `isStaleByTime` and it takes `enabled` into account
300 if (this.getObserversCount() > 0) {
301 return this.observers.some(
302 (observer) => observer.getCurrentResult().isStale,
303 )
304 }
305β
306 return this.state.data === undefined || this.state.isInvalidated
307 }
308β
309 isStaleByTime(staleTime: StaleTime = 0): boolean {
310 // no data is always stale
311 if (this.state.data === undefined) {
312 return true
313 }
314 // static is never stale
315 if (staleTime === 'static') {
316 return false
317 }
318 // if the query is invalidated, it is stale
319 if (this.state.isInvalidated) {
320 return true
321 }
322β
323 return !timeUntilStale(this.state.dataUpdatedAt, staleTime)
324 }
325β
326 onFocus(): void {
327 const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())
328β
329 observer?.refetch({ cancelRefetch: false })
330β
331 // Continue fetch if currently paused
332 this.#retryer?.continue()
333 }
334β
335 onOnline(): void {
336 const observer = this.observers.find((x) => x.shouldFetchOnReconnect())
337β
338 observer?.refetch({ cancelRefetch: false })
339β
340 // Continue fetch if currently paused
341 this.#retryer?.continue()
342 }
343β
344 addObserver(observer: QueryObserver<any, any, any, any, any>): void {
345 if (!this.observers.includes(observer)) {
346 this.observers.push(observer)
347β
348 // Stop the query from being garbage collected
349 this.clearGcTimeout()
350β
351 this.#cache.notify({ type: 'observerAdded', query: this, observer })
352 }
353 }
354β
355 removeObserver(observer: QueryObserver<any, any, any, any, any>): void {
356 if (this.observers.includes(observer)) {
357 this.observers = this.observers.filter((x) => x !== observer)
358β
359 if (!this.observers.length) {
360 // If the transport layer does not support cancellation
361 // we'll let the query continue so the result can be cached
362 if (this.#retryer) {
363 if (this.#abortSignalConsumed) {
364 this.#retryer.cancel({ revert: true })
365 } else {
366 this.#retryer.cancelRetry()
367 }
368 }
369β
370 this.scheduleGc()
371 }
372β
373 this.#cache.notify({ type: 'observerRemoved', query: this, observer })
374 }
375 }
376β
377 getObserversCount(): number {
378 return this.observers.length
379 }
380β
381 invalidate(): void {
382 if (!this.state.isInvalidated) {
383 this.#dispatch({ type: 'invalidate' })
384 }
385 }
386β
387 async fetch(
388 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
389 fetchOptions?: FetchOptions<TQueryFnData>,
390 ): Promise<TData> {
391 if (
392 this.state.fetchStatus !== 'idle' &&
393 // If the promise in the retyer is already rejected, we have to definitely
394 // re-start the fetch; there is a chance that the query is still in a
395 // pending state when that happens
396 this.#retryer?.status() !== 'rejected'
397 ) {
398 if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {
399 // Silently cancel current fetch if the user wants to cancel refetch
400 this.cancel({ silent: true })
401 } else if (this.#retryer) {
402 // make sure that retries that were potentially cancelled due to unmounts can continue
403 this.#retryer.continueRetry()
404 // Return current promise if we are already fetching
405 return this.#retryer.promise
406 }
407 }
408β
409 // Update config if passed, otherwise the config from the last execution is used
410 if (options) {
411 this.setOptions(options)
412 }
413β
414 // Use the options from the first observer with a query function if no function is found.
415 // This can happen when the query is hydrated or created with setQueryData.
416 if (!this.options.queryFn) {
417 const observer = this.observers.find((x) => x.options.queryFn)
418 if (observer) {
419 this.setOptions(observer.options)
420 }
421 }
422β
423 if (process.env.NODE_ENV !== 'production') {
424 if (!Array.isArray(this.options.queryKey)) {
425 console.error(
426 `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']`,
427 )
428 }
429 }
430β
431 const abortController = new AbortController()
432β
433 // Adds an enumerable signal property to the object that
434 // which sets abortSignalConsumed to true when the signal
435 // is read.
436 const addSignalProperty = (object: unknown) => {
437 Object.defineProperty(object, 'signal', {
438 enumerable: true,
439 get: () => {
440 this.#abortSignalConsumed = true
441 return abortController.signal
442 },
443 })
444 }
445β
446 // Create fetch function
447 const fetchFn = () => {
448 const queryFn = ensureQueryFn(this.options, fetchOptions)
449β
450 // Create query function context
451 const createQueryFnContext = (): QueryFunctionContext<TQueryKey> => {
452 const queryFnContext: OmitKeyof<
453 QueryFunctionContext<TQueryKey>,
454 'signal'
455 > = {
456 client: this.#client,
457 queryKey: this.queryKey,
458 meta: this.meta,
459 }
460 addSignalProperty(queryFnContext)
461 return queryFnContext as QueryFunctionContext<TQueryKey>
462 }
463β
464 const queryFnContext = createQueryFnContext()
465β
466 this.#abortSignalConsumed = false
467 if (this.options.persister) {
468 return this.options.persister(
469 queryFn,
470 queryFnContext,
471 this as unknown as Query,
472 )
473 }
474β
475 return queryFn(queryFnContext)
476 }
477β
478 // Trigger behavior hook
479 const createFetchContext = (): FetchContext<
480 TQueryFnData,
481 TError,
482 TData,
483 TQueryKey
484 > => {
485 const context: OmitKeyof<
486 FetchContext<TQueryFnData, TError, TData, TQueryKey>,
487 'signal'
488 > = {
489 fetchOptions,
490 options: this.options,
491 queryKey: this.queryKey,
492 client: this.#client,
493 state: this.state,
494 fetchFn,
495 }
496β
497 addSignalProperty(context)
498 return context as FetchContext<TQueryFnData, TError, TData, TQueryKey>
499 }
500β
501 const context = createFetchContext()
502β
503 this.options.behavior?.onFetch(context, this as unknown as Query)
504β
505 // Store state in case the current fetch needs to be reverted
506 this.#revertState = this.state
507β
508 // Set to fetching state if not already in it
509 if (
510 this.state.fetchStatus === 'idle' ||
511 this.state.fetchMeta !== context.fetchOptions?.meta
512 ) {
513 this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })
514 }
515β
516 // Try to fetch the data
517 this.#retryer = createRetryer({
518 initialPromise: fetchOptions?.initialPromise as
519 | Promise<TData>
520 | undefined,
521 fn: context.fetchFn as () => Promise<TData>,
522 onCancel: (error) => {
523 if (error instanceof CancelledError && error.revert) {
524 this.setState({
525 ...this.#revertState,
526 fetchStatus: 'idle' as const,
527 })
528 }
529 abortController.abort()
530 },
531 onFail: (failureCount, error) => {
532 this.#dispatch({ type: 'failed', failureCount, error })
533 },
534 onPause: () => {
535 this.#dispatch({ type: 'pause' })
536 },
537 onContinue: () => {
538 this.#dispatch({ type: 'continue' })
539 },
540 retry: context.options.retry,
541 retryDelay: context.options.retryDelay,
542 networkMode: context.options.networkMode,
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 data: action.data,
639 dataUpdateCount: state.dataUpdateCount + 1,
640 dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),
641 error: null,
642 isInvalidated: false,
643 status: 'success' as const,
644 ...(!action.manual && {
645 fetchStatus: 'idle' as const,
646 fetchFailureCount: 0,
647 fetchFailureReason: null,
648 }),
649 }
650 // If fetching ends successfully, we don't need revertState as a fallback anymore.
651 // For manual updates, capture the state to revert to it in case of a cancellation.
652 this.#revertState = action.manual ? newState : undefined
653β
654 return newState
655 case 'error':
656 const error = action.error
657 return {
658 ...state,
659 error,
660 errorUpdateCount: state.errorUpdateCount + 1,
661 errorUpdatedAt: Date.now(),
662 fetchFailureCount: state.fetchFailureCount + 1,
663 fetchFailureReason: error,
664 fetchStatus: 'idle',
665 status: 'error',
666 }
667 case 'invalidate':
668 return {
669 ...state,
670 isInvalidated: true,
671 }
672 case 'setState':
673 return {
674 ...state,
675 ...action.state,
676 }
677 }
678 }
679β
680 this.state = reducer(this.state)
681β
682 notifyManager.batch(() => {
683 this.observers.forEach((observer) => {
684 observer.onQueryUpdate()
685 })
686β
687 this.#cache.notify({ query: this, type: 'updated', action })
688 })
689 }
690}
691β
692export function fetchState<
693 TQueryFnData,
694 TError,
695 TData,
696 TQueryKey extends QueryKey,
697>(
698 data: TData | undefined,
699 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
700) {
701 return {
702 fetchFailureCount: 0,
703 fetchFailureReason: null,
704 fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',
705 ...(data === undefined &&
706 ({
707 error: null,
708 status: 'pending',
709 } as const)),
710 } as const
711}
712β
713function getDefaultState<
714 TQueryFnData,
715 TError,
716 TData,
717 TQueryKey extends QueryKey,
718>(
719 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
720): QueryState<TData, TError> {
721 const data =
722 typeof options.initialData === 'function'
723 ? (options.initialData as InitialDataFunction<TData>)()
724 : options.initialData
725β
726 const hasData = data !== undefined
727β
728 const initialDataUpdatedAt = hasData
729 ? typeof options.initialDataUpdatedAt === 'function'
730 ? (options.initialDataUpdatedAt as () => number | undefined)()
731 : options.initialDataUpdatedAt
732 : 0
733β
734 return {
735 data,
736 dataUpdateCount: 0,
737 dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,
738 error: null,
739 errorUpdateCount: 0,
740 errorUpdatedAt: 0,
741 fetchFailureCount: 0,
742 fetchFailureReason: null,
743 fetchMeta: null,
744 isInvalidated: false,
745 status: hasData ? 'success' : 'pending',
746 fetchStatus: 'idle',
747 }
748}