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