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

query.ts

752 lines19.5 KB

1import {
2 ensureQueryFn,
3 isServer,
4 isValidTimeout,
5 noop,
6 replaceData,
7 resolveEnabled,
8 skipToken,
9 timeUntilStale,
10} from './utils'
11import { notifyManager } from './notifyManager'
12import { canFetch, createRetryer, isCancelledError } from './retryer'
13import { Removable } from './removable'
14import type {
15 CancelOptions,
16 DefaultError,
17 FetchStatus,
18 InitialDataFunction,
19 OmitKeyof,
20 QueryFunction,
21 QueryFunctionContext,
22 QueryKey,
23 QueryMeta,
24 QueryOptions,
25 QueryStatus,
26 SetDataOptions,
27 StaleTime,
28} from './types'
29import type { QueryCache } from './queryCache'
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 cache: QueryCache
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 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 #retryer?: Retryer<TData>
174 observers: Array<QueryObserver<any, any, any, any, any>>
175 #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
176 #abortSignalConsumed: boolean
177 #staleTimeoutId?: ReturnType<typeof setTimeout>
178​
179 constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {
180 super()
181​
182 this.#abortSignalConsumed = false
183 this.#defaultOptions = config.defaultOptions
184 this.#initOptions(config.options)
185 this.observers = []
186 this.#cache = config.cache
187 this.queryKey = config.queryKey
188 this.queryHash = config.queryHash
189 this.#initialState = getDefaultState(this.options)
190 this.state = config.state ?? this.#initialState
191​
192 this.scheduleGc()
193​
194 const nextStaleTime = this.#resolveStaleTime(this.options.staleTime)
195 if (nextStaleTime === 0) {
196 this.#initialState.isInvalidated = true
197 }
198​
199 this.#updateStaleTimeout(nextStaleTime)
200 }
201 get meta(): QueryMeta | undefined {
202 return this.options.meta
203 }
204​
205 get promise(): Promise<TData> | undefined {
206 return this.#retryer?.promise
207 }
208​
209 #initOptions(
210 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
211 ): void {
212 this.options = { ...this.#defaultOptions, ...options }
213​
214 this.updateGcTime(this.options.gcTime)
215 }
216​
217 setOptions(
218 nextOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
219 ): void {
220 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
221 const prevStaleTime = this.options?.staleTime
222 this.#initOptions(nextOptions)
223​
224 const nextStaleTime = this.#resolveStaleTime(nextOptions?.staleTime)
225​
226 // Update stale interval if needed
227 if (nextStaleTime !== this.#resolveStaleTime(prevStaleTime)) {
228 this.#updateStaleTimeout(nextStaleTime)
229 }
230 }
231​
232 protected optionalRemove() {
233 if (!this.observers.length && this.state.fetchStatus === 'idle') {
234 this.#cache.remove(this)
235 }
236 }
237​
238 setData(
239 newData: TData,
240 options?: SetDataOptions & { manual: boolean },
241 ): TData {
242 const data = replaceData(this.state.data, newData, this.options)
243​
244 // Set data and mark it as cached
245 this.#dispatch({
246 data,
247 type: 'success',
248 dataUpdatedAt: options?.updatedAt,
249 manual: options?.manual,
250 })
251​
252 return data
253 }
254​
255 setState(
256 state: Partial<QueryState<TData, TError>>,
257 setStateOptions?: SetStateOptions,
258 ): void {
259 this.#dispatch({ type: 'setState', state, setStateOptions })
260 }
261​
262 cancel(options?: CancelOptions): Promise<void> {
263 const promise = this.#retryer?.promise
264 this.#retryer?.cancel(options)
265 return promise ? promise.then(noop).catch(noop) : Promise.resolve()
266 }
267​
268 destroy(): void {
269 super.destroy()
270​
271 this.#clearStaleTimeout()
272 this.cancel({ silent: true })
273 }
274​
275 reset(): void {
276 this.destroy()
277 this.setState(this.#initialState)
278 }
279​
280 isActive(): boolean {
281 return this.observers.some(
282 (observer) => resolveEnabled(observer.options.enabled, this) !== false,
283 )
284 }
285​
286 isDisabled(): boolean {
287 if (this.getObserversCount() > 0) {
288 return !this.isActive()
289 }
290 // if a query has no observers, it should still be considered disabled if it never attempted a fetch
291 return (
292 this.options.queryFn === skipToken ||
293 this.state.dataUpdateCount + this.state.errorUpdateCount === 0
294 )
295 }
296​
297 isStale(): boolean {
298 return this.state.isInvalidated || this.state.data === undefined
299 }
300​
301 onFocus(): void {
302 const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())
303​
304 observer?.refetch({ cancelRefetch: false })
305​
306 // Continue fetch if currently paused
307 this.#retryer?.continue()
308 }
309​
310 onOnline(): void {
311 const observer = this.observers.find((x) => x.shouldFetchOnReconnect())
312​
313 observer?.refetch({ cancelRefetch: false })
314​
315 // Continue fetch if currently paused
316 this.#retryer?.continue()
317 }
318​
319 addObserver(observer: QueryObserver<any, any, any, any, any>): void {
320 if (!this.observers.includes(observer)) {
321 this.observers.push(observer)
322​
323 // Stop the query from being garbage collected
324 this.clearGcTimeout()
325​
326 this.#cache.notify({ type: 'observerAdded', query: this, observer })
327 }
328 }
329​
330 removeObserver(observer: QueryObserver<any, any, any, any, any>): void {
331 if (this.observers.includes(observer)) {
332 this.observers = this.observers.filter((x) => x !== observer)
333​
334 if (!this.observers.length) {
335 // If the transport layer does not support cancellation
336 // we'll let the query continue so the result can be cached
337 if (this.#retryer) {
338 if (this.#abortSignalConsumed) {
339 this.#retryer.cancel({ revert: true })
340 } else {
341 this.#retryer.cancelRetry()
342 }
343 }
344​
345 this.scheduleGc()
346 }
347​
348 this.#cache.notify({ type: 'observerRemoved', query: this, observer })
349 }
350 }
351​
352 getObserversCount(): number {
353 return this.observers.length
354 }
355​
356 invalidate(): void {
357 if (!this.state.isInvalidated) {
358 this.#dispatch({ type: 'invalidate' })
359 }
360 }
361​
362 fetch(
363 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
364 fetchOptions?: FetchOptions<TQueryFnData>,
365 ): Promise<TData> {
366 if (this.state.fetchStatus !== 'idle') {
367 if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {
368 // Silently cancel current fetch if the user wants to cancel refetch
369 this.cancel({ silent: true })
370 } else if (this.#retryer) {
371 // make sure that retries that were potentially cancelled due to unmounts can continue
372 this.#retryer.continueRetry()
373 // Return current promise if we are already fetching
374 return this.#retryer.promise
375 }
376 }
377​
378 // Update config if passed, otherwise the config from the last execution is used
379 if (options) {
380 this.setOptions(options)
381 }
382​
383 // Use the options from the first observer with a query function if no function is found.
384 // This can happen when the query is hydrated or created with setQueryData.
385 if (!this.options.queryFn) {
386 const observer = this.observers.find((x) => x.options.queryFn)
387 if (observer) {
388 this.setOptions(observer.options)
389 }
390 }
391​
392 if (process.env.NODE_ENV !== 'production') {
393 if (!Array.isArray(this.options.queryKey)) {
394 console.error(
395 `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']`,
396 )
397 }
398 }
399​
400 const abortController = new AbortController()
401​
402 // Adds an enumerable signal property to the object that
403 // which sets abortSignalConsumed to true when the signal
404 // is read.
405 const addSignalProperty = (object: unknown) => {
406 Object.defineProperty(object, 'signal', {
407 enumerable: true,
408 get: () => {
409 this.#abortSignalConsumed = true
410 return abortController.signal
411 },
412 })
413 }
414​
415 // Create fetch function
416 const fetchFn = () => {
417 const queryFn = ensureQueryFn(this.options, fetchOptions)
418​
419 // Create query function context
420 const queryFnContext: OmitKeyof<
421 QueryFunctionContext<TQueryKey>,
422 'signal'
423 > = {
424 queryKey: this.queryKey,
425 meta: this.meta,
426 }
427​
428 addSignalProperty(queryFnContext)
429​
430 this.#abortSignalConsumed = false
431 if (this.options.persister) {
432 return this.options.persister(
433 queryFn as QueryFunction<any>,
434 queryFnContext as QueryFunctionContext<TQueryKey>,
435 this as unknown as Query,
436 )
437 }
438​
439 return queryFn(queryFnContext as QueryFunctionContext<TQueryKey>)
440 }
441​
442 // Trigger behavior hook
443 const context: OmitKeyof<
444 FetchContext<TQueryFnData, TError, TData, TQueryKey>,
445 'signal'
446 > = {
447 fetchOptions,
448 options: this.options,
449 queryKey: this.queryKey,
450 state: this.state,
451 fetchFn,
452 }
453​
454 addSignalProperty(context)
455​
456 this.options.behavior?.onFetch(
457 context as FetchContext<TQueryFnData, TError, TData, TQueryKey>,
458 this as unknown as Query,
459 )
460​
461 // Store state in case the current fetch needs to be reverted
462 this.#revertState = this.state
463​
464 // Set to fetching state if not already in it
465 if (
466 this.state.fetchStatus === 'idle' ||
467 this.state.fetchMeta !== context.fetchOptions?.meta
468 ) {
469 this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })
470 }
471​
472 const onError = (error: TError | { silent?: boolean }) => {
473 // Optimistically update state if needed
474 if (!(isCancelledError(error) && error.silent)) {
475 this.#dispatch({
476 type: 'error',
477 error: error as TError,
478 })
479 }
480​
481 if (!isCancelledError(error)) {
482 // Notify cache callback
483 this.#cache.config.onError?.(
484 error as any,
485 this as Query<any, any, any, any>,
486 )
487 this.#cache.config.onSettled?.(
488 this.state.data,
489 error as any,
490 this as Query<any, any, any, any>,
491 )
492 }
493​
494 // Schedule query gc after fetching
495 this.scheduleGc()
496 }
497​
498 // Try to fetch the data
499 this.#retryer = createRetryer({
500 initialPromise: fetchOptions?.initialPromise as
501 | Promise<TData>
502 | undefined,
503 fn: context.fetchFn as () => Promise<TData>,
504 abort: abortController.abort.bind(abortController),
505 onSuccess: (data) => {
506 if (data === undefined) {
507 if (process.env.NODE_ENV !== 'production') {
508 console.error(
509 `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,
510 )
511 }
512 onError(new Error(`${this.queryHash} data is undefined`) as any)
513 return
514 }
515​
516 try {
517 this.setData(data)
518 } catch (error) {
519 onError(error as TError)
520 return
521 }
522​
523 // Notify cache callback
524 this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)
525 this.#cache.config.onSettled?.(
526 data,
527 this.state.error as any,
528 this as Query<any, any, any, any>,
529 )
530​
531 // Schedule query gc after fetching
532 this.scheduleGc()
533 },
534 onError,
535 onFail: (failureCount, error) => {
536 this.#dispatch({ type: 'failed', failureCount, error })
537 },
538 onPause: () => {
539 this.#dispatch({ type: 'pause' })
540 },
541 onContinue: () => {
542 this.#dispatch({ type: 'continue' })
543 },
544 retry: context.options.retry,
545 retryDelay: context.options.retryDelay,
546 networkMode: context.options.networkMode,
547 canRun: () => true,
548 })
549​
550 return this.#retryer.start()
551 }
552​
553 #dispatch(action: Action<TData, TError>): void {
554 const reducer = (
555 state: QueryState<TData, TError>,
556 ): QueryState<TData, TError> => {
557 switch (action.type) {
558 case 'failed':
559 return {
560 ...state,
561 fetchFailureCount: action.failureCount,
562 fetchFailureReason: action.error,
563 }
564 case 'pause':
565 return {
566 ...state,
567 fetchStatus: 'paused',
568 }
569 case 'continue':
570 return {
571 ...state,
572 fetchStatus: 'fetching',
573 }
574 case 'fetch':
575 return {
576 ...state,
577 ...fetchState(state.data, this.options),
578 fetchMeta: action.meta ?? null,
579 }
580 case 'success':
581 return {
582 ...state,
583 data: action.data,
584 dataUpdateCount: state.dataUpdateCount + 1,
585 dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),
586 error: null,
587 isInvalidated: false,
588 status: 'success',
589 ...(!action.manual && {
590 fetchStatus: 'idle',
591 fetchFailureCount: 0,
592 fetchFailureReason: null,
593 }),
594 }
595 case 'error':
596 const error = action.error
597​
598 if (isCancelledError(error) && error.revert && this.#revertState) {
599 return { ...this.#revertState, fetchStatus: 'idle' }
600 }
601​
602 return {
603 ...state,
604 error,
605 errorUpdateCount: state.errorUpdateCount + 1,
606 errorUpdatedAt: Date.now(),
607 fetchFailureCount: state.fetchFailureCount + 1,
608 fetchFailureReason: error,
609 fetchStatus: 'idle',
610 status: 'error',
611 }
612 case 'invalidate':
613 return {
614 ...state,
615 isInvalidated: true,
616 }
617 case 'setState':
618 return {
619 ...state,
620 ...action.state,
621 }
622 }
623 }
624​
625 this.state = reducer(this.state)
626​
627 const nextStaleTime = this.#resolveStaleTime(this.options.staleTime)
628 if (nextStaleTime === 0) {
629 this.state.isInvalidated = true
630 } else if (!this.isStale()) {
631 this.#updateStaleTimeout(nextStaleTime)
632 }
633​
634 notifyManager.batch(() => {
635 this.observers.forEach((observer) => {
636 observer.onQueryUpdate()
637 })
638​
639 if (this.#cache.get(this.queryHash)) {
640 this.#cache.notify({ query: this, type: 'updated', action })
641 }
642 })
643 }
644​
645 #resolveStaleTime(
646 staleTime: StaleTime<TQueryFnData, TError, TData, TQueryKey> | undefined,
647 ): number {
648 return typeof staleTime === 'function' ? staleTime(this) : (staleTime ?? 0)
649 }
650​
651 #updateStaleTimeout(staleTime: number): void {
652 this.#clearStaleTimeout()
653​
654 const time = timeUntilStale(this.state.dataUpdatedAt, staleTime)
655​
656 if (process.env.NODE_ENV !== 'production') {
657 const staleTimes = this.observers.map((observer) =>
658 this.#resolveStaleTime(observer.options.staleTime),
659 )
660 staleTimes.push(staleTime)
661​
662 if (new Set(staleTimes).size > 1) {
663 console.error(
664 `Multiple observers with different staleTimes are attached to the this query: ${this.queryHash}. The staleTime of the query will be determined by the last observer.`,
665 )
666 }
667 }
668​
669 const newInvalidated = time === 0
670 if (this.state.isInvalidated !== newInvalidated) {
671 this.#dispatch({
672 type: 'setState',
673 state: { isInvalidated: newInvalidated },
674 })
675 }
676​
677 if (isServer || !isValidTimeout(staleTime) || newInvalidated) {
678 return
679 }
680​
681 // The timeout is sometimes triggered 1 ms before the stale time expiration.
682 // To mitigate this issue we always add 1 ms to the timeout.
683 this.#staleTimeoutId = setTimeout(() => {
684 this.invalidate()
685 }, time + 1)
686 }
687​
688 #clearStaleTimeout(): void {
689 if (this.#staleTimeoutId) {
690 clearTimeout(this.#staleTimeoutId)
691 this.#staleTimeoutId = undefined
692 }
693 }
695​
696export function fetchState<
697 TQueryFnData,
698 TError,
699 TData,
700 TQueryKey extends QueryKey,
701>(
702 data: TData | undefined,
703 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
704) {
705 return {
706 fetchFailureCount: 0,
707 fetchFailureReason: null,
708 fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',
709 ...(data === undefined &&
710 ({
711 error: null,
712 status: 'pending',
713 } as const)),
714 } as const
716​
717function getDefaultState<
718 TQueryFnData,
719 TError,
720 TData,
721 TQueryKey extends QueryKey,
722>(
723 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
724): QueryState<TData, TError> {
725 const data =
726 typeof options.initialData === 'function'
727 ? (options.initialData as InitialDataFunction<TData>)()
728 : options.initialData
729​
730 const hasData = data !== undefined
731​
732 const initialDataUpdatedAt = hasData
733 ? typeof options.initialDataUpdatedAt === 'function'
734 ? (options.initialDataUpdatedAt as () => number | undefined)()
735 : options.initialDataUpdatedAt
736 : 0
737​
738 return {
739 data,
740 dataUpdateCount: 0,
741 dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,
742 error: null,
743 errorUpdateCount: 0,
744 errorUpdatedAt: 0,
745 fetchFailureCount: 0,
746 fetchFailureReason: null,
747 fetchMeta: null,
748 isInvalidated: !hasData,
749 status: hasData ? 'success' : 'pending',
750 fetchStatus: 'idle',
751 }