Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

query.ts

784 lines20.9 KB

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>
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
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>
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
90​
91export type FetchDirection = 'forward' | 'backward'
92​
93export interface FetchMeta {
94 fetchMore?: { direction: FetchDirection }
96​
97export interface FetchOptions<TData = unknown> {
98 cancelRefetch?: boolean
99 meta?: FetchMeta
100 initialPromise?: Promise<TData>
102​
103interface FailedAction<TError> {
104 type: 'failed'
105 failureCount: number
106 error: TError
108​
109interface FetchAction {
110 type: 'fetch'
111 meta?: FetchMeta
113​
114interface SuccessAction<TData> {
115 data: TData | undefined
116 type: 'success'
117 dataUpdatedAt?: number
118 manual?: boolean
120​
121interface ErrorAction<TError> {
122 type: 'error'
123 error: TError
125​
126interface InvalidateAction {
127 type: 'invalidate'
129​
130interface PauseAction {
131 type: 'pause'
133​
134interface ContinueAction {
135 type: 'continue'
137​
138interface SetStateAction<TData, TError> {
139 type: 'setState'
140 state: Partial<QueryState<TData, TError>>
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 const index = this.observers.indexOf(observer)
364 if (index !== -1) {
365 this.observers.splice(index, 1)
366​
367 if (!this.observers.length) {
368 // If the transport layer does not support cancellation
369 // we'll let the query continue so the result can be cached
370 if (this.#retryer) {
371 if (this.#abortSignalConsumed || this.#isInitialPausedFetch()) {
372 this.#retryer.cancel({ revert: true })
373 } else {
374 this.#retryer.cancelRetry()
375 }
376 }
377​
378 this.scheduleGc()
379 }
380​
381 this.#cache.notify({ type: 'observerRemoved', query: this, observer })
382 }
383 }
384​
385 getObserversCount(): number {
386 return this.observers.length
387 }
388​
389 #isInitialPausedFetch(): boolean {
390 return (
391 this.state.fetchStatus === 'paused' && this.state.status === 'pending'
392 )
393 }
394​
395 invalidate(): void {
396 if (!this.state.isInvalidated) {
397 this.#dispatch({ type: 'invalidate' })
398 }
399 }
400​
401 async fetch(
402 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
403 fetchOptions?: FetchOptions<TQueryFnData>,
404 ): Promise<TData> {
405 if (
406 this.state.fetchStatus !== 'idle' &&
407 // If the promise in the retryer is already rejected, we have to definitely
408 // re-start the fetch; there is a chance that the query is still in a
409 // pending state when that happens
410 this.#retryer?.status() !== 'rejected'
411 ) {
412 if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {
413 // Silently cancel current fetch if the user wants to cancel refetch
414 this.cancel({ silent: true })
415 } else if (this.#retryer) {
416 // make sure that retries that were potentially cancelled due to unmounts can continue
417 this.#retryer.continueRetry()
418 // Return current promise if we are already fetching
419 return this.#retryer.promise
420 }
421 }
422​
423 // Update config if passed, otherwise the config from the last execution is used
424 if (options) {
425 this.setOptions(options)
426 }
427​
428 // Use the options from the first observer with a query function if no function is found.
429 // This can happen when the query is hydrated or created with setQueryData.
430 if (!this.options.queryFn) {
431 const observer = this.observers.find((x) => x.options.queryFn)
432 if (observer) {
433 this.setOptions(observer.options)
434 }
435 }
436​
437 if (process.env.NODE_ENV !== 'production') {
438 if (!Array.isArray(this.options.queryKey)) {
439 console.error(
440 `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']`,
441 )
442 }
443 }
444​
445 const abortController = new AbortController()
446​
447 // Adds an enumerable signal property to the object that
448 // which sets abortSignalConsumed to true when the signal
449 // is read.
450 const addSignalProperty = (object: unknown) => {
451 Object.defineProperty(object, 'signal', {
452 enumerable: true,
453 get: () => {
454 this.#abortSignalConsumed = true
455 return abortController.signal
456 },
457 })
458 }
459​
460 // Create fetch function
461 const fetchFn = () => {
462 const queryFn = ensureQueryFn(this.options, fetchOptions)
463​
464 // Create query function context
465 const createQueryFnContext = (): QueryFunctionContext<TQueryKey> => {
466 const queryFnContext: OmitKeyof<
467 QueryFunctionContext<TQueryKey>,
468 'signal'
469 > = {
470 client: this.#client,
471 queryKey: this.queryKey,
472 meta: this.meta,
473 }
474 addSignalProperty(queryFnContext)
475 return queryFnContext as QueryFunctionContext<TQueryKey>
476 }
477​
478 const queryFnContext = createQueryFnContext()
479​
480 this.#abortSignalConsumed = false
481 if (this.options.persister) {
482 return this.options.persister(
483 queryFn,
484 queryFnContext,
485 this as unknown as Query,
486 )
487 }
488​
489 return queryFn(queryFnContext)
490 }
491​
492 // Trigger behavior hook
493 const createFetchContext = (): FetchContext<
494 TQueryFnData,
495 TError,
496 TData,
497 TQueryKey
498 > => {
499 const context: OmitKeyof<
500 FetchContext<TQueryFnData, TError, TData, TQueryKey>,
501 'signal'
502 > = {
503 fetchOptions,
504 options: this.options,
505 queryKey: this.queryKey,
506 client: this.#client,
507 state: this.state,
508 fetchFn,
509 }
510​
511 addSignalProperty(context)
512 return context as FetchContext<TQueryFnData, TError, TData, TQueryKey>
513 }
514​
515 const context = createFetchContext()
516​
517 const behavior =
518 this.#queryType === 'infinite'
519 ? (infiniteQueryBehavior(
520 (this.options as { pages?: number }).pages,
521 ) as QueryBehavior<TQueryFnData, TError, TData, TQueryKey>)
522 : this.options.behavior
523 behavior?.onFetch(context, this as unknown as Query)
524​
525 // Store state in case the current fetch needs to be reverted
526 this.#revertState = this.state
527​
528 // Set to fetching state if not already in it
529 if (
530 this.state.fetchStatus === 'idle' ||
531 this.state.fetchMeta !== context.fetchOptions?.meta
532 ) {
533 this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })
534 }
535​
536 // Try to fetch the data
537 const retryer = (this.#retryer = createRetryer({
538 initialPromise: fetchOptions?.initialPromise as
539 | Promise<TData>
540 | undefined,
541 fn: context.fetchFn as () => Promise<TData>,
542 onCancel: (error) => {
543 if (error instanceof CancelledError && error.revert) {
544 this.setState({
545 ...this.#revertState,
546 fetchStatus: 'idle' as const,
547 })
548 }
549 abortController.abort()
550 },
551 onFail: (failureCount, error) => {
552 this.#dispatch({ type: 'failed', failureCount, error })
553 },
554 onPause: () => {
555 this.#dispatch({ type: 'pause' })
556 },
557 onContinue: () => {
558 this.#dispatch({ type: 'continue' })
559 },
560 retry: context.options.retry,
561 retryDelay: context.options.retryDelay,
562 networkMode: context.options.networkMode,
563 canRun: () => true,
564 }))
565​
566 try {
567 const data = await retryer.start()
568 // this is more of a runtime guard
569 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
570 if (data === undefined) {
571 if (process.env.NODE_ENV !== 'production') {
572 console.error(
573 `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,
574 )
575 }
576 throw new Error(`${this.queryHash} data is undefined`)
577 }
578​
579 this.setData(data)
580​
581 // Notify cache callback
582 this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)
583 this.#cache.config.onSettled?.(
584 data,
585 this.state.error as any,
586 this as Query<any, any, any, any>,
587 )
588 return data
589 } catch (error) {
590 if (error instanceof CancelledError) {
591 if (error.silent) {
592 // silent cancellation implies a new fetch is going to be started,
593 // so we piggyback onto that promise
594 return this.#retryer.promise
595 } else if (error.revert) {
596 // transform error into reverted state data
597 // if the initial fetch was cancelled, we have no data, so we have
598 // to get reject with a CancelledError
599 if (this.state.data === undefined) {
600 throw error
601 }
602 return this.state.data
603 }
604 }
605 this.#dispatch({
606 type: 'error',
607 error: error as TError,
608 })
609​
610 // Notify cache callback
611 this.#cache.config.onError?.(
612 error as any,
613 this as Query<any, any, any, any>,
614 )
615 this.#cache.config.onSettled?.(
616 this.state.data,
617 error as any,
618 this as Query<any, any, any, any>,
619 )
620​
621 throw error // rethrow the error for further handling
622 } finally {
623 // The settled retryer's promise would otherwise pin this fetch's raw
624 // result (a second copy after structural sharing) for the query's lifetime
625 if (this.#retryer === retryer) {
626 this.#retryer = undefined
627 }
628 // Schedule query gc after fetching
629 this.scheduleGc()
630 }
631 }
632​
633 #dispatch(action: Action<TData, TError>): void {
634 const reducer = (
635 state: QueryState<TData, TError>,
636 ): QueryState<TData, TError> => {
637 switch (action.type) {
638 case 'failed':
639 return {
640 ...state,
641 fetchFailureCount: action.failureCount,
642 fetchFailureReason: action.error,
643 }
644 case 'pause':
645 return {
646 ...state,
647 fetchStatus: 'paused',
648 }
649 case 'continue':
650 return {
651 ...state,
652 fetchStatus: 'fetching',
653 }
654 case 'fetch':
655 return {
656 ...state,
657 ...fetchState(state.data, this.options),
658 fetchMeta: action.meta ?? null,
659 }
660 case 'success':
661 const newState = {
662 ...state,
663 ...successState(action.data, action.dataUpdatedAt),
664 dataUpdateCount: state.dataUpdateCount + 1,
665 ...(!action.manual && {
666 fetchStatus: 'idle' as const,
667 fetchFailureCount: 0,
668 fetchFailureReason: null,
669 }),
670 }
671 // If fetching ends successfully, we don't need revertState as a fallback anymore.
672 // For manual updates, capture the state to revert to it in case of a cancellation.
673 this.#revertState = action.manual ? newState : undefined
674​
675 return newState
676 case 'error':
677 const error = action.error
678 return {
679 ...state,
680 error,
681 errorUpdateCount: state.errorUpdateCount + 1,
682 errorUpdatedAt: Date.now(),
683 fetchFailureCount: state.fetchFailureCount + 1,
684 fetchFailureReason: error,
685 fetchStatus: 'idle',
686 status: 'error',
687 // flag existing data as invalidated if we get a background error
688 // note that "no data" always means stale so we can set unconditionally here
689 isInvalidated: true,
690 }
691 case 'invalidate':
692 return {
693 ...state,
694 isInvalidated: true,
695 }
696 case 'setState':
697 return {
698 ...state,
699 ...action.state,
700 }
701 }
702 }
703​
704 this.state = reducer(this.state)
705​
706 notifyManager.batch(() => {
707 // Keep the current iteration stable if an observer unsubscribes
708 // synchronously while it is being notified.
709 this.observers.slice().forEach((observer) => {
710 observer.onQueryUpdate()
711 })
712​
713 this.#cache.notify({ query: this, type: 'updated', action })
714 })
715 }
717​
718export function fetchState<
719 TQueryFnData,
720 TError,
721 TData,
722 TQueryKey extends QueryKey,
723>(
724 data: TData | undefined,
725 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
726) {
727 return {
728 fetchFailureCount: 0,
729 fetchFailureReason: null,
730 fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',
731 ...(data === undefined &&
732 ({
733 error: null,
734 status: 'pending',
735 } as const)),
736 } as const
738​
739function successState<TData>(data: TData | undefined, dataUpdatedAt?: number) {
740 return {
741 data,
742 dataUpdatedAt: dataUpdatedAt ?? Date.now(),
743 error: null,
744 isInvalidated: false,
745 status: 'success' as const,
746 }
748​
749function getDefaultState<
750 TQueryFnData,
751 TError,
752 TData,
753 TQueryKey extends QueryKey,
754>(
755 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
756): QueryState<TData, TError> {
757 const data =
758 typeof options.initialData === 'function'
759 ? (options.initialData as InitialDataFunction<TData>)()
760 : options.initialData
761​
762 const hasData = data !== undefined
763​
764 const initialDataUpdatedAt = hasData
765 ? typeof options.initialDataUpdatedAt === 'function'
766 ? options.initialDataUpdatedAt()
767 : options.initialDataUpdatedAt
768 : 0
769​
770 return {
771 data,
772 dataUpdateCount: 0,
773 dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,
774 error: null,
775 errorUpdateCount: 0,
776 errorUpdatedAt: 0,
777 fetchFailureCount: 0,
778 fetchFailureReason: null,
779 fetchMeta: null,
780 isInvalidated: false,
781 status: hasData ? 'success' : 'pending',
782 fetchStatus: 'idle',
783 }