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

query.ts

767 lines20.2 KB

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>
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
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>
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
89​
90export type FetchDirection = 'forward' | 'backward'
91​
92export interface FetchMeta {
93 fetchMore?: { direction: FetchDirection }
95​
96export interface FetchOptions<TData = unknown> {
97 cancelRefetch?: boolean
98 meta?: FetchMeta
99 initialPromise?: Promise<TData>
101​
102interface FailedAction<TError> {
103 type: 'failed'
104 failureCount: number
105 error: TError
107​
108interface FetchAction {
109 type: 'fetch'
110 meta?: FetchMeta
112​
113interface SuccessAction<TData> {
114 data: TData | undefined
115 type: 'success'
116 dataUpdatedAt?: number
117 manual?: boolean
119​
120interface ErrorAction<TError> {
121 type: 'error'
122 error: TError
124​
125interface InvalidateAction {
126 type: 'invalidate'
128​
129interface PauseAction {
130 type: 'pause'
132​
133interface ContinueAction {
134 type: 'continue'
136​
137interface SetStateAction<TData, TError> {
138 type: 'setState'
139 state: Partial<QueryState<TData, TError>>
140 setStateOptions?: SetStateOptions
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
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 get resetState(): QueryState<TData, TError> {
264 return this.#initialState
265 }
266​
267 reset(): void {
268 this.destroy()
269 this.setState(this.resetState)
270 }
271​
272 isActive(): boolean {
273 return this.observers.some(
274 (observer) => resolveEnabled(observer.options.enabled, this) !== false,
275 )
276 }
277​
278 isDisabled(): boolean {
279 if (this.getObserversCount() > 0) {
280 return !this.isActive()
281 }
282 // if a query has no observers, it should still be considered disabled if it never attempted a fetch
283 return this.options.queryFn === skipToken || !this.isFetched()
284 }
285​
286 isFetched() {
287 return this.state.dataUpdateCount + this.state.errorUpdateCount > 0
288 }
289​
290 isStatic(): boolean {
291 if (this.getObserversCount() > 0) {
292 return this.observers.some(
293 (observer) =>
294 resolveStaleTime(observer.options.staleTime, this) === 'static',
295 )
296 }
297​
298 return false
299 }
300​
301 isStale(): boolean {
302 // check observers first, their `isStale` has the source of truth
303 // calculated with `isStaleByTime` and it takes `enabled` into account
304 if (this.getObserversCount() > 0) {
305 return this.observers.some(
306 (observer) => observer.getCurrentResult().isStale,
307 )
308 }
309​
310 return this.state.data === undefined || this.state.isInvalidated
311 }
312​
313 isStaleByTime(staleTime: StaleTime = 0): boolean {
314 // no data is always stale
315 if (this.state.data === undefined) {
316 return true
317 }
318 // static is never stale
319 if (staleTime === 'static') {
320 return false
321 }
322 // if the query is invalidated, it is stale
323 if (this.state.isInvalidated) {
324 return true
325 }
326​
327 return !timeUntilStale(this.state.dataUpdatedAt, staleTime)
328 }
329​
330 onFocus(): void {
331 const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())
332​
333 observer?.refetch({ cancelRefetch: false })
334​
335 // Continue fetch if currently paused
336 this.#retryer?.continue()
337 }
338​
339 onOnline(): void {
340 const observer = this.observers.find((x) => x.shouldFetchOnReconnect())
341​
342 observer?.refetch({ cancelRefetch: false })
343​
344 // Continue fetch if currently paused
345 this.#retryer?.continue()
346 }
347​
348 addObserver(observer: QueryObserver<any, any, any, any, any>): void {
349 if (!this.observers.includes(observer)) {
350 this.observers.push(observer)
351​
352 // Stop the query from being garbage collected
353 this.clearGcTimeout()
354​
355 this.#cache.notify({ type: 'observerAdded', query: this, observer })
356 }
357 }
358​
359 removeObserver(observer: QueryObserver<any, any, any, any, any>): void {
360 if (this.observers.includes(observer)) {
361 this.observers = this.observers.filter((x) => x !== observer)
362​
363 if (!this.observers.length) {
364 // If the transport layer does not support cancellation
365 // we'll let the query continue so the result can be cached
366 if (this.#retryer) {
367 if (this.#abortSignalConsumed || this.#isInitialPausedFetch()) {
368 this.#retryer.cancel({ revert: true })
369 } else {
370 this.#retryer.cancelRetry()
371 }
372 }
373​
374 this.scheduleGc()
375 }
376​
377 this.#cache.notify({ type: 'observerRemoved', query: this, observer })
378 }
379 }
380​
381 getObserversCount(): number {
382 return this.observers.length
383 }
384​
385 #isInitialPausedFetch(): boolean {
386 return (
387 this.state.fetchStatus === 'paused' && this.state.status === 'pending'
388 )
389 }
390​
391 invalidate(): void {
392 if (!this.state.isInvalidated) {
393 this.#dispatch({ type: 'invalidate' })
394 }
395 }
396​
397 async fetch(
398 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
399 fetchOptions?: FetchOptions<TQueryFnData>,
400 ): Promise<TData> {
401 if (
402 this.state.fetchStatus !== 'idle' &&
403 // If the promise in the retryer is already rejected, we have to definitely
404 // re-start the fetch; there is a chance that the query is still in a
405 // pending state when that happens
406 this.#retryer?.status() !== 'rejected'
407 ) {
408 if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {
409 // Silently cancel current fetch if the user wants to cancel refetch
410 this.cancel({ silent: true })
411 } else if (this.#retryer) {
412 // make sure that retries that were potentially cancelled due to unmounts can continue
413 this.#retryer.continueRetry()
414 // Return current promise if we are already fetching
415 return this.#retryer.promise
416 }
417 }
418​
419 // Update config if passed, otherwise the config from the last execution is used
420 if (options) {
421 this.setOptions(options)
422 }
423​
424 // Use the options from the first observer with a query function if no function is found.
425 // This can happen when the query is hydrated or created with setQueryData.
426 if (!this.options.queryFn) {
427 const observer = this.observers.find((x) => x.options.queryFn)
428 if (observer) {
429 this.setOptions(observer.options)
430 }
431 }
432​
433 if (process.env.NODE_ENV !== 'production') {
434 if (!Array.isArray(this.options.queryKey)) {
435 console.error(
436 `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']`,
437 )
438 }
439 }
440​
441 const abortController = new AbortController()
442​
443 // Adds an enumerable signal property to the object that
444 // which sets abortSignalConsumed to true when the signal
445 // is read.
446 const addSignalProperty = (object: unknown) => {
447 Object.defineProperty(object, 'signal', {
448 enumerable: true,
449 get: () => {
450 this.#abortSignalConsumed = true
451 return abortController.signal
452 },
453 })
454 }
455​
456 // Create fetch function
457 const fetchFn = () => {
458 const queryFn = ensureQueryFn(this.options, fetchOptions)
459​
460 // Create query function context
461 const createQueryFnContext = (): QueryFunctionContext<TQueryKey> => {
462 const queryFnContext: OmitKeyof<
463 QueryFunctionContext<TQueryKey>,
464 'signal'
465 > = {
466 client: this.#client,
467 queryKey: this.queryKey,
468 meta: this.meta,
469 }
470 addSignalProperty(queryFnContext)
471 return queryFnContext as QueryFunctionContext<TQueryKey>
472 }
473​
474 const queryFnContext = createQueryFnContext()
475​
476 this.#abortSignalConsumed = false
477 if (this.options.persister) {
478 return this.options.persister(
479 queryFn,
480 queryFnContext,
481 this as unknown as Query,
482 )
483 }
484​
485 return queryFn(queryFnContext)
486 }
487​
488 // Trigger behavior hook
489 const createFetchContext = (): FetchContext<
490 TQueryFnData,
491 TError,
492 TData,
493 TQueryKey
494 > => {
495 const context: OmitKeyof<
496 FetchContext<TQueryFnData, TError, TData, TQueryKey>,
497 'signal'
498 > = {
499 fetchOptions,
500 options: this.options,
501 queryKey: this.queryKey,
502 client: this.#client,
503 state: this.state,
504 fetchFn,
505 }
506​
507 addSignalProperty(context)
508 return context as FetchContext<TQueryFnData, TError, TData, TQueryKey>
509 }
510​
511 const context = createFetchContext()
512​
513 this.options.behavior?.onFetch(context, this as unknown as Query)
514​
515 // Store state in case the current fetch needs to be reverted
516 this.#revertState = this.state
517​
518 // Set to fetching state if not already in it
519 if (
520 this.state.fetchStatus === 'idle' ||
521 this.state.fetchMeta !== context.fetchOptions?.meta
522 ) {
523 this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })
524 }
525​
526 // Try to fetch the data
527 this.#retryer = createRetryer({
528 initialPromise: fetchOptions?.initialPromise as
529 | Promise<TData>
530 | undefined,
531 fn: context.fetchFn as () => Promise<TData>,
532 onCancel: (error) => {
533 if (error instanceof CancelledError && error.revert) {
534 this.setState({
535 ...this.#revertState,
536 fetchStatus: 'idle' as const,
537 })
538 }
539 abortController.abort()
540 },
541 onFail: (failureCount, error) => {
542 this.#dispatch({ type: 'failed', failureCount, error })
543 },
544 onPause: () => {
545 this.#dispatch({ type: 'pause' })
546 },
547 onContinue: () => {
548 this.#dispatch({ type: 'continue' })
549 },
550 retry: context.options.retry,
551 retryDelay: context.options.retryDelay,
552 networkMode: context.options.networkMode,
553 canRun: () => true,
554 })
555​
556 try {
557 const data = await this.#retryer.start()
558 // this is more of a runtime guard
559 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
560 if (data === undefined) {
561 if (process.env.NODE_ENV !== 'production') {
562 console.error(
563 `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,
564 )
565 }
566 throw new Error(`${this.queryHash} data is undefined`)
567 }
568​
569 this.setData(data)
570​
571 // Notify cache callback
572 this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)
573 this.#cache.config.onSettled?.(
574 data,
575 this.state.error as any,
576 this as Query<any, any, any, any>,
577 )
578 return data
579 } catch (error) {
580 if (error instanceof CancelledError) {
581 if (error.silent) {
582 // silent cancellation implies a new fetch is going to be started,
583 // so we piggyback onto that promise
584 return this.#retryer.promise
585 } else if (error.revert) {
586 // transform error into reverted state data
587 // if the initial fetch was cancelled, we have no data, so we have
588 // to get reject with a CancelledError
589 if (this.state.data === undefined) {
590 throw error
591 }
592 return this.state.data
593 }
594 }
595 this.#dispatch({
596 type: 'error',
597 error: error as TError,
598 })
599​
600 // Notify cache callback
601 this.#cache.config.onError?.(
602 error as any,
603 this as Query<any, any, any, any>,
604 )
605 this.#cache.config.onSettled?.(
606 this.state.data,
607 error as any,
608 this as Query<any, any, any, any>,
609 )
610​
611 throw error // rethrow the error for further handling
612 } finally {
613 // Schedule query gc after fetching
614 this.scheduleGc()
615 }
616 }
617​
618 #dispatch(action: Action<TData, TError>): void {
619 const reducer = (
620 state: QueryState<TData, TError>,
621 ): QueryState<TData, TError> => {
622 switch (action.type) {
623 case 'failed':
624 return {
625 ...state,
626 fetchFailureCount: action.failureCount,
627 fetchFailureReason: action.error,
628 }
629 case 'pause':
630 return {
631 ...state,
632 fetchStatus: 'paused',
633 }
634 case 'continue':
635 return {
636 ...state,
637 fetchStatus: 'fetching',
638 }
639 case 'fetch':
640 return {
641 ...state,
642 ...fetchState(state.data, this.options),
643 fetchMeta: action.meta ?? null,
644 }
645 case 'success':
646 const newState = {
647 ...state,
648 ...successState(action.data, action.dataUpdatedAt),
649 dataUpdateCount: state.dataUpdateCount + 1,
650 ...(!action.manual && {
651 fetchStatus: 'idle' as const,
652 fetchFailureCount: 0,
653 fetchFailureReason: null,
654 }),
655 }
656 // If fetching ends successfully, we don't need revertState as a fallback anymore.
657 // For manual updates, capture the state to revert to it in case of a cancellation.
658 this.#revertState = action.manual ? newState : undefined
659​
660 return newState
661 case 'error':
662 const error = action.error
663 return {
664 ...state,
665 error,
666 errorUpdateCount: state.errorUpdateCount + 1,
667 errorUpdatedAt: Date.now(),
668 fetchFailureCount: state.fetchFailureCount + 1,
669 fetchFailureReason: error,
670 fetchStatus: 'idle',
671 status: 'error',
672 // flag existing data as invalidated if we get a background error
673 // note that "no data" always means stale so we can set unconditionally here
674 isInvalidated: true,
675 }
676 case 'invalidate':
677 return {
678 ...state,
679 isInvalidated: true,
680 }
681 case 'setState':
682 return {
683 ...state,
684 ...action.state,
685 }
686 }
687 }
688​
689 this.state = reducer(this.state)
690​
691 notifyManager.batch(() => {
692 this.observers.forEach((observer) => {
693 observer.onQueryUpdate()
694 })
695​
696 this.#cache.notify({ query: this, type: 'updated', action })
697 })
698 }
700​
701export function fetchState<
702 TQueryFnData,
703 TError,
704 TData,
705 TQueryKey extends QueryKey,
706>(
707 data: TData | undefined,
708 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
709) {
710 return {
711 fetchFailureCount: 0,
712 fetchFailureReason: null,
713 fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',
714 ...(data === undefined &&
715 ({
716 error: null,
717 status: 'pending',
718 } as const)),
719 } as const
721​
722function successState<TData>(data: TData | undefined, dataUpdatedAt?: number) {
723 return {
724 data,
725 dataUpdatedAt: dataUpdatedAt ?? Date.now(),
726 error: null,
727 isInvalidated: false,
728 status: 'success' as const,
729 }
731​
732function getDefaultState<
733 TQueryFnData,
734 TError,
735 TData,
736 TQueryKey extends QueryKey,
737>(
738 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
739): QueryState<TData, TError> {
740 const data =
741 typeof options.initialData === 'function'
742 ? (options.initialData as InitialDataFunction<TData>)()
743 : options.initialData
744​
745 const hasData = data !== undefined
746​
747 const initialDataUpdatedAt = hasData
748 ? typeof options.initialDataUpdatedAt === 'function'
749 ? options.initialDataUpdatedAt()
750 : options.initialDataUpdatedAt
751 : 0
752​
753 return {
754 data,
755 dataUpdateCount: 0,
756 dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,
757 error: null,
758 errorUpdateCount: 0,
759 errorUpdatedAt: 0,
760 fetchFailureCount: 0,
761 fetchFailureReason: null,
762 fetchMeta: null,
763 isInvalidated: false,
764 status: hasData ? 'success' : 'pending',
765 fetchStatus: 'idle',
766 }