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

query.ts

780 lines20.8 KB

1import {
2 ensureQueryFn,
3 noop,
4 replaceData,
5 resolveQueryValue,
6 skipToken,
7 timeUntilStale,
8} from './utils'
9import { notifyManager } from './notifyManager'
10import { CancelledError, canFetch, createRetryer } from './retryer'
11import { Removable } from './removable'
12import { infiniteQueryBehavior } from './infiniteQueryBehavior'
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>>
141​
142export type Action<TData, TError> =
143 | ContinueAction
144 | ErrorAction<TError>
145 | FailedAction<TError>
146 | FetchAction
147 | InvalidateAction
148 | PauseAction
149 | SetStateAction<TData, TError>
150 | SuccessAction<TData>
151​
152// CLASS
153​
154export class Query<
155 TQueryFnData = unknown,
156 TError = DefaultError,
157 TData = TQueryFnData,
158 TQueryKey extends QueryKey = QueryKey,
159> extends Removable {
160 queryKey: TQueryKey
161 queryHash: string
162 options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
163 state: QueryState<TData, TError>
164 #queryType?: 'infinite'
165​
166 #initialState: QueryState<TData, TError>
167 #revertState?: QueryState<TData, TError>
168 #cache: QueryCache
169 #client: QueryClient
170 #retryer?: Retryer<TData>
171 observers: Array<QueryObserver<any, any, any, any, any>>
172 #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
173 #abortSignalConsumed: boolean
174​
175 constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {
176 super()
177​
178 this.#abortSignalConsumed = false
179 this.#defaultOptions = config.defaultOptions
180 this.setOptions(config.options)
181 this.observers = []
182 this.#client = config.client
183 this.#cache = this.#client.getQueryCache()
184 this.queryKey = config.queryKey
185 this.queryHash = config.queryHash
186 this.#initialState = getDefaultState(this.options)
187 this.state = config.state ?? this.#initialState
188 this.scheduleGc()
189 }
190 get meta(): QueryMeta | undefined {
191 return this.options.meta
192 }
193​
194 get queryType() {
195 return this.#queryType
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 if (options?._type) {
208 this.#queryType = options._type
209 }
210​
211 this.updateGcTime(this.options.gcTime)
212​
213 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
214 if (this.state && this.state.data === undefined) {
215 const defaultState = getDefaultState(this.options)
216 if (defaultState.data !== undefined) {
217 this.setState(
218 successState(defaultState.data, defaultState.dataUpdatedAt),
219 )
220 this.#initialState = defaultState
221 }
222 }
223 }
224​
225 protected optionalRemove() {
226 if (!this.observers.length && this.state.fetchStatus === 'idle') {
227 this.#cache.remove(this)
228 }
229 }
230​
231 setData(
232 newData: TData,
233 options?: SetDataOptions & { manual: boolean },
234 ): TData {
235 const data = replaceData(this.state.data, newData, this.options)
236​
237 // Set data and mark it as cached
238 this.#dispatch({
239 data,
240 type: 'success',
241 dataUpdatedAt: options?.updatedAt,
242 manual: options?.manual,
243 })
244​
245 return data
246 }
247​
248 setState(state: Partial<QueryState<TData, TError>>): void {
249 this.#dispatch({ type: 'setState', state })
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 get resetState(): QueryState<TData, TError> {
265 return this.#initialState
266 }
267​
268 reset(): void {
269 this.destroy()
270 this.setState(this.resetState)
271 }
272​
273 isActive(): boolean {
274 return this.observers.some(
275 (observer) => resolveQueryValue(observer.options.enabled, this) !== false,
276 )
277 }
278​
279 isDisabled(): boolean {
280 if (this.getObserversCount() > 0) {
281 return !this.isActive()
282 }
283 // if a query has no observers, it should still be considered disabled if it never attempted a fetch
284 return this.options.queryFn === skipToken || !this.isFetched()
285 }
286​
287 isFetched() {
288 return this.state.dataUpdateCount + this.state.errorUpdateCount > 0
289 }
290​
291 isStatic(): boolean {
292 if (this.getObserversCount() > 0) {
293 return this.observers.some(
294 (observer) =>
295 resolveQueryValue(observer.options.staleTime, this) === 'static',
296 )
297 }
298​
299 return false
300 }
301​
302 isStale(): boolean {
303 // check observers first, their `isStale` has the source of truth
304 // calculated with `isStaleByTime` and it takes `enabled` into account
305 if (this.getObserversCount() > 0) {
306 return this.observers.some(
307 (observer) => observer.getCurrentResult().isStale,
308 )
309 }
310​
311 return this.state.data === undefined || this.state.isInvalidated
312 }
313​
314 isStaleByTime(staleTime: StaleTime = 0): boolean {
315 // no data is always stale
316 if (this.state.data === undefined) {
317 return true
318 }
319 // static is never stale
320 if (staleTime === 'static') {
321 return false
322 }
323 // if the query is invalidated, it is stale
324 if (this.state.isInvalidated) {
325 return true
326 }
327​
328 return !timeUntilStale(this.state.dataUpdatedAt, staleTime)
329 }
330​
331 onFocus(): void {
332 const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())
333​
334 observer?.refetch({ cancelRefetch: false })
335​
336 // Continue fetch if currently paused
337 this.#retryer?.continue()
338 }
339​
340 onOnline(): void {
341 const observer = this.observers.find((x) => x.shouldFetchOnReconnect())
342​
343 observer?.refetch({ cancelRefetch: false })
344​
345 // Continue fetch if currently paused
346 this.#retryer?.continue()
347 }
348​
349 addObserver(observer: QueryObserver<any, any, any, any, any>): void {
350 if (!this.observers.includes(observer)) {
351 this.observers.push(observer)
352​
353 // Stop the query from being garbage collected
354 this.clearGcTimeout()
355​
356 this.#cache.notify({ type: 'observerAdded', query: this, observer })
357 }
358 }
359​
360 removeObserver(observer: QueryObserver<any, any, any, any, any>): void {
361 const index = this.observers.indexOf(observer)
362 if (index !== -1) {
363 this.observers.splice(index, 1)
364​
365 if (!this.observers.length) {
366 // If the transport layer does not support cancellation
367 // we'll let the query continue so the result can be cached
368 if (this.#retryer) {
369 if (
370 this.#abortSignalConsumed ||
371 (this.state.fetchStatus === 'paused' &&
372 this.state.status === 'pending')
373 ) {
374 this.#retryer.cancel({ revert: true })
375 } else {
376 this.#retryer.cancelRetry()
377 }
378 }
379​
380 this.scheduleGc()
381 }
382​
383 this.#cache.notify({ type: 'observerRemoved', query: this, observer })
384 }
385 }
386​
387 getObserversCount(): number {
388 return this.observers.length
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 const behavior =
514 this.#queryType === 'infinite'
515 ? (infiniteQueryBehavior(
516 (this.options as { pages?: number }).pages,
517 ) as QueryBehavior<TQueryFnData, TError, TData, TQueryKey>)
518 : this.options.behavior
519 behavior?.onFetch(context, this as unknown as Query)
520​
521 // Store state in case the current fetch needs to be reverted
522 this.#revertState = this.state
523​
524 // Set to fetching state if not already in it
525 if (
526 this.state.fetchStatus === 'idle' ||
527 this.state.fetchMeta !== context.fetchOptions?.meta
528 ) {
529 this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })
530 }
531​
532 // Try to fetch the data
533 const retryer = (this.#retryer = createRetryer({
534 initialPromise: fetchOptions?.initialPromise as
535 | Promise<TData>
536 | undefined,
537 fn: context.fetchFn as () => Promise<TData>,
538 onCancel: (error) => {
539 if (error instanceof CancelledError && error.revert) {
540 this.setState({
541 ...this.#revertState,
542 fetchStatus: 'idle' as const,
543 })
544 }
545 abortController.abort()
546 },
547 onFail: (failureCount, error) => {
548 this.#dispatch({ type: 'failed', failureCount, error })
549 },
550 onPause: () => {
551 this.#dispatch({ type: 'pause' })
552 },
553 onContinue: () => {
554 this.#dispatch({ type: 'continue' })
555 },
556 retry: context.options.retry,
557 retryDelay: context.options.retryDelay,
558 networkMode: context.options.networkMode,
559 canRun: () => true,
560 }))
561​
562 try {
563 const data = await retryer.start()
564 // this is more of a runtime guard
565 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
566 if (data === undefined) {
567 if (process.env.NODE_ENV !== 'production') {
568 console.error(
569 `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,
570 )
571 }
572 throw new Error(`${this.queryHash} data is undefined`)
573 }
574​
575 this.setData(data)
576​
577 // Notify cache callback
578 this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)
579 this.#cache.config.onSettled?.(
580 data,
581 this.state.error as any,
582 this as Query<any, any, any, any>,
583 )
584 return data
585 } catch (error) {
586 if (error instanceof CancelledError) {
587 if (error.silent) {
588 // silent cancellation implies a new fetch is going to be started,
589 // so we piggyback onto that promise
590 return this.#retryer.promise
591 } else if (error.revert) {
592 // transform error into reverted state data
593 // if the initial fetch was cancelled, we have no data, so we have
594 // to get reject with a CancelledError
595 if (this.state.data === undefined) {
596 throw error
597 }
598 return this.state.data
599 }
600 }
601 this.#dispatch({
602 type: 'error',
603 error: error as TError,
604 })
605​
606 // Notify cache callback
607 this.#cache.config.onError?.(
608 error as any,
609 this as Query<any, any, any, any>,
610 )
611 this.#cache.config.onSettled?.(
612 this.state.data,
613 error as any,
614 this as Query<any, any, any, any>,
615 )
616​
617 throw error // rethrow the error for further handling
618 } finally {
619 // The settled retryer's promise would otherwise pin this fetch's raw
620 // result (a second copy after structural sharing) for the query's lifetime
621 if (this.#retryer === retryer) {
622 this.#retryer = undefined
623 }
624 // Schedule query gc after fetching
625 this.scheduleGc()
626 }
627 }
628​
629 #dispatch(action: Action<TData, TError>): void {
630 const reducer = (
631 state: QueryState<TData, TError>,
632 ): QueryState<TData, TError> => {
633 switch (action.type) {
634 case 'failed':
635 return {
636 ...state,
637 fetchFailureCount: action.failureCount,
638 fetchFailureReason: action.error,
639 }
640 case 'pause':
641 return {
642 ...state,
643 fetchStatus: 'paused',
644 }
645 case 'continue':
646 return {
647 ...state,
648 fetchStatus: 'fetching',
649 }
650 case 'fetch':
651 return {
652 ...state,
653 ...fetchState(state.data, this.options),
654 fetchMeta: action.meta ?? null,
655 }
656 case 'success':
657 const newState = {
658 ...state,
659 ...successState(action.data, action.dataUpdatedAt),
660 dataUpdateCount: state.dataUpdateCount + 1,
661 ...(!action.manual && {
662 fetchStatus: 'idle' as const,
663 fetchFailureCount: 0,
664 fetchFailureReason: null,
665 }),
666 }
667 // If fetching ends successfully, we don't need revertState as a fallback anymore.
668 // For manual updates, capture the state to revert to it in case of a cancellation.
669 this.#revertState = action.manual ? newState : undefined
670​
671 return newState
672 case 'error':
673 const error = action.error
674 return {
675 ...state,
676 error,
677 errorUpdateCount: state.errorUpdateCount + 1,
678 errorUpdatedAt: Date.now(),
679 fetchFailureCount: state.fetchFailureCount + 1,
680 fetchFailureReason: error,
681 fetchStatus: 'idle',
682 status: 'error',
683 // flag existing data as invalidated if we get a background error
684 // note that "no data" always means stale so we can set unconditionally here
685 isInvalidated: true,
686 }
687 case 'invalidate':
688 return {
689 ...state,
690 isInvalidated: true,
691 }
692 case 'setState':
693 return {
694 ...state,
695 ...action.state,
696 }
697 }
698 }
699​
700 this.state = reducer(this.state)
701​
702 notifyManager.batch(() => {
703 // Keep the current iteration stable if an observer unsubscribes
704 // synchronously while it is being notified.
705 this.observers.slice().forEach((observer) => {
706 observer.onQueryUpdate()
707 })
708​
709 this.#cache.notify({ query: this, type: 'updated', action })
710 })
711 }
713​
714export function fetchState<
715 TQueryFnData,
716 TError,
717 TData,
718 TQueryKey extends QueryKey,
719>(
720 data: TData | undefined,
721 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
722) {
723 return {
724 fetchFailureCount: 0,
725 fetchFailureReason: null,
726 fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',
727 ...(data === undefined &&
728 ({
729 error: null,
730 status: 'pending',
731 } as const)),
732 } as const
734​
735function successState<TData>(data: TData | undefined, dataUpdatedAt?: number) {
736 return {
737 data,
738 dataUpdatedAt: dataUpdatedAt ?? Date.now(),
739 error: null,
740 isInvalidated: false,
741 status: 'success' as const,
742 }
744​
745function getDefaultState<
746 TQueryFnData,
747 TError,
748 TData,
749 TQueryKey extends QueryKey,
750>(
751 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
752): QueryState<TData, TError> {
753 const data =
754 typeof options.initialData === 'function'
755 ? (options.initialData as InitialDataFunction<TData>)()
756 : options.initialData
757​
758 const hasData = data !== undefined
759​
760 const initialDataUpdatedAt = hasData
761 ? typeof options.initialDataUpdatedAt === 'function'
762 ? options.initialDataUpdatedAt()
763 : options.initialDataUpdatedAt
764 : 0
765​
766 return {
767 data,
768 dataUpdateCount: 0,
769 dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,
770 error: null,
771 errorUpdateCount: 0,
772 errorUpdatedAt: 0,
773 fetchFailureCount: 0,
774 fetchFailureReason: null,
775 fetchMeta: null,
776 isInvalidated: false,
777 status: hasData ? 'success' : 'pending',
778 fetchStatus: 'idle',
779 }