Open History to see the last commit
1import {
2 ensureQueryFn,
3 noop,
4 replaceData,
5 resolveEnabled,
6 skipToken,
7 timeUntilStale,
8} from './utils'
9import { notifyManager } from './notifyManager'
10import { canFetch, createRetryer, isCancelledError } from './retryer'
11import { Removable } from './removable'
12import type {
13 CancelOptions,
14 DefaultError,
15 FetchStatus,
16 InitialDataFunction,
17 OmitKeyof,
18 QueryFunction,
19 QueryFunctionContext,
20 QueryKey,
21 QueryMeta,
22 QueryOptions,
23 QueryStatus,
24 SetDataOptions,
25} from './types'
26import type { QueryCache } from './queryCache'
27import type { QueryObserver } from './queryObserver'
28import type { Retryer } from './retryer'
29β
30// TYPES
31β
32interface QueryConfig<
33 TQueryFnData,
34 TError,
35 TData,
36 TQueryKey extends QueryKey = QueryKey,
37> {
38 cache: QueryCache
39 queryKey: TQueryKey
40 queryHash: string
41 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
42 defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
43 state?: QueryState<TData, TError>
44}
45β
46export interface QueryState<TData = unknown, TError = DefaultError> {
47 data: TData | undefined
48 dataUpdateCount: number
49 dataUpdatedAt: number
50 error: TError | null
51 errorUpdateCount: number
52 errorUpdatedAt: number
53 fetchFailureCount: number
54 fetchFailureReason: TError | null
55 fetchMeta: FetchMeta | null
56 isInvalidated: boolean
57 status: QueryStatus
58 fetchStatus: FetchStatus
59}
60β
61export interface FetchContext<
62 TQueryFnData,
63 TError,
64 TData,
65 TQueryKey extends QueryKey = QueryKey,
66> {
67 fetchFn: () => unknown | Promise<unknown>
68 fetchOptions?: FetchOptions
69 signal: AbortSignal
70 options: QueryOptions<TQueryFnData, TError, TData, any>
71 queryKey: TQueryKey
72 state: QueryState<TData, TError>
73}
74β
75export interface QueryBehavior<
76 TQueryFnData = unknown,
77 TError = DefaultError,
78 TData = TQueryFnData,
79 TQueryKey extends QueryKey = QueryKey,
80> {
81 onFetch: (
82 context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,
83 query: Query,
84 ) => void
85}
86β
87export type FetchDirection = 'forward' | 'backward'
88β
89export interface FetchMeta {
90 fetchMore?: { direction: FetchDirection }
91}
92β
93export interface FetchOptions<TData = unknown> {
94 cancelRefetch?: boolean
95 meta?: FetchMeta
96 initialPromise?: Promise<TData>
97}
98β
99interface FailedAction<TError> {
100 type: 'failed'
101 failureCount: number
102 error: TError
103}
104β
105interface FetchAction {
106 type: 'fetch'
107 meta?: FetchMeta
108}
109β
110interface SuccessAction<TData> {
111 data: TData | undefined
112 type: 'success'
113 dataUpdatedAt?: number
114 manual?: boolean
115}
116β
117interface ErrorAction<TError> {
118 type: 'error'
119 error: TError
120}
121β
122interface InvalidateAction {
123 type: 'invalidate'
124}
125β
126interface PauseAction {
127 type: 'pause'
128}
129β
130interface ContinueAction {
131 type: 'continue'
132}
133β
134interface SetStateAction<TData, TError> {
135 type: 'setState'
136 state: Partial<QueryState<TData, TError>>
137 setStateOptions?: SetStateOptions
138}
139β
140export type Action<TData, TError> =
141 | ContinueAction
142 | ErrorAction<TError>
143 | FailedAction<TError>
144 | FetchAction
145 | InvalidateAction
146 | PauseAction
147 | SetStateAction<TData, TError>
148 | SuccessAction<TData>
149β
150export interface SetStateOptions {
151 meta?: any
152}
153β
154// CLASS
155β
156export class Query<
157 TQueryFnData = unknown,
158 TError = DefaultError,
159 TData = TQueryFnData,
160 TQueryKey extends QueryKey = QueryKey,
161> extends Removable {
162 queryKey: TQueryKey
163 queryHash: string
164 options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
165 state: QueryState<TData, TError>
166β
167 #initialState: QueryState<TData, TError>
168 #revertState?: QueryState<TData, TError>
169 #cache: QueryCache
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.#cache = config.cache
183 this.queryKey = config.queryKey
184 this.queryHash = config.queryHash
185 this.#initialState = getDefaultState(this.options)
186 this.state = config.state ?? this.#initialState
187 this.scheduleGc()
188 }
189 get meta(): QueryMeta | undefined {
190 return this.options.meta
191 }
192β
193 get promise(): Promise<TData> | undefined {
194 return this.#retryer?.promise
195 }
196β
197 setOptions(
198 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
199 ): void {
200 this.options = { ...this.#defaultOptions, ...options }
201β
202 this.updateGcTime(this.options.gcTime)
203 }
204β
205 protected optionalRemove() {
206 if (!this.observers.length && this.state.fetchStatus === 'idle') {
207 this.#cache.remove(this)
208 }
209 }
210β
211 setData(
212 newData: TData,
213 options?: SetDataOptions & { manual: boolean },
214 ): TData {
215 const data = replaceData(this.state.data, newData, this.options)
216β
217 // Set data and mark it as cached
218 this.#dispatch({
219 data,
220 type: 'success',
221 dataUpdatedAt: options?.updatedAt,
222 manual: options?.manual,
223 })
224β
225 return data
226 }
227β
228 setState(
229 state: Partial<QueryState<TData, TError>>,
230 setStateOptions?: SetStateOptions,
231 ): void {
232 this.#dispatch({ type: 'setState', state, setStateOptions })
233 }
234β
235 cancel(options?: CancelOptions): Promise<void> {
236 const promise = this.#retryer?.promise
237 this.#retryer?.cancel(options)
238 return promise ? promise.then(noop).catch(noop) : Promise.resolve()
239 }
240β
241 destroy(): void {
242 super.destroy()
243β
244 this.cancel({ silent: true })
245 }
246β
247 reset(): void {
248 this.destroy()
249 this.setState(this.#initialState)
250 }
251β
252 isActive(): boolean {
253 return this.observers.some(
254 (observer) => resolveEnabled(observer.options.enabled, this) !== false,
255 )
256 }
257β
258 isDisabled(): boolean {
259 if (this.getObserversCount() > 0) {
260 return !this.isActive()
261 }
262 // if a query has no observers, it should still be considered disabled if it never attempted a fetch
263 return (
264 this.options.queryFn === skipToken ||
265 this.state.dataUpdateCount + this.state.errorUpdateCount === 0
266 )
267 }
268β
269 isStale(): boolean {
270 if (this.state.isInvalidated) {
271 return true
272 }
273β
274 if (this.getObserversCount() > 0) {
275 return this.observers.some(
276 (observer) => observer.getCurrentResult().isStale,
277 )
278 }
279β
280 return this.state.data === undefined
281 }
282β
283 isStaleByTime(staleTime = 0): boolean {
284 return (
285 this.state.isInvalidated ||
286 this.state.data === undefined ||
287 !timeUntilStale(this.state.dataUpdatedAt, staleTime)
288 )
289 }
290β
291 onFocus(): void {
292 const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())
293β
294 observer?.refetch({ cancelRefetch: false })
295β
296 // Continue fetch if currently paused
297 this.#retryer?.continue()
298 }
299β
300 onOnline(): void {
301 const observer = this.observers.find((x) => x.shouldFetchOnReconnect())
302β
303 observer?.refetch({ cancelRefetch: false })
304β
305 // Continue fetch if currently paused
306 this.#retryer?.continue()
307 }
308β
309 addObserver(observer: QueryObserver<any, any, any, any, any>): void {
310 if (!this.observers.includes(observer)) {
311 this.observers.push(observer)
312β
313 // Stop the query from being garbage collected
314 this.clearGcTimeout()
315β
316 this.#cache.notify({ type: 'observerAdded', query: this, observer })
317 }
318 }
319β
320 removeObserver(observer: QueryObserver<any, any, any, any, any>): void {
321 if (this.observers.includes(observer)) {
322 this.observers = this.observers.filter((x) => x !== observer)
323β
324 if (!this.observers.length) {
325 // If the transport layer does not support cancellation
326 // we'll let the query continue so the result can be cached
327 if (this.#retryer) {
328 if (this.#abortSignalConsumed) {
329 this.#retryer.cancel({ revert: true })
330 } else {
331 this.#retryer.cancelRetry()
332 }
333 }
334β
335 this.scheduleGc()
336 }
337β
338 this.#cache.notify({ type: 'observerRemoved', query: this, observer })
339 }
340 }
341β
342 getObserversCount(): number {
343 return this.observers.length
344 }
345β
346 invalidate(): void {
347 if (!this.state.isInvalidated) {
348 this.#dispatch({ type: 'invalidate' })
349 }
350 }
351β
352 fetch(
353 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
354 fetchOptions?: FetchOptions<TQueryFnData>,
355 ): Promise<TData> {
356 if (this.state.fetchStatus !== 'idle') {
357 if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {
358 // Silently cancel current fetch if the user wants to cancel refetch
359 this.cancel({ silent: true })
360 } else if (this.#retryer) {
361 // make sure that retries that were potentially cancelled due to unmounts can continue
362 this.#retryer.continueRetry()
363 // Return current promise if we are already fetching
364 return this.#retryer.promise
365 }
366 }
367β
368 // Update config if passed, otherwise the config from the last execution is used
369 if (options) {
370 this.setOptions(options)
371 }
372β
373 // Use the options from the first observer with a query function if no function is found.
374 // This can happen when the query is hydrated or created with setQueryData.
375 if (!this.options.queryFn) {
376 const observer = this.observers.find((x) => x.options.queryFn)
377 if (observer) {
378 this.setOptions(observer.options)
379 }
380 }
381β
382 if (process.env.NODE_ENV !== 'production') {
383 if (!Array.isArray(this.options.queryKey)) {
384 console.error(
385 `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']`,
386 )
387 }
388 }
389β
390 const abortController = new AbortController()
391β
392 // Adds an enumerable signal property to the object that
393 // which sets abortSignalConsumed to true when the signal
394 // is read.
395 const addSignalProperty = (object: unknown) => {
396 Object.defineProperty(object, 'signal', {
397 enumerable: true,
398 get: () => {
399 this.#abortSignalConsumed = true
400 return abortController.signal
401 },
402 })
403 }
404β
405 // Create fetch function
406 const fetchFn = () => {
407 const queryFn = ensureQueryFn(this.options, fetchOptions)
408β
409 // Create query function context
410 const queryFnContext: OmitKeyof<
411 QueryFunctionContext<TQueryKey>,
412 'signal'
413 > = {
414 queryKey: this.queryKey,
415 meta: this.meta,
416 }
417β
418 addSignalProperty(queryFnContext)
419β
420 this.#abortSignalConsumed = false
421 if (this.options.persister) {
422 return this.options.persister(
423 queryFn as QueryFunction<any>,
424 queryFnContext as QueryFunctionContext<TQueryKey>,
425 this as unknown as Query,
426 )
427 }
428β
429 return queryFn(queryFnContext as QueryFunctionContext<TQueryKey>)
430 }
431β
432 // Trigger behavior hook
433 const context: OmitKeyof<
434 FetchContext<TQueryFnData, TError, TData, TQueryKey>,
435 'signal'
436 > = {
437 fetchOptions,
438 options: this.options,
439 queryKey: this.queryKey,
440 state: this.state,
441 fetchFn,
442 }
443β
444 addSignalProperty(context)
445β
446 this.options.behavior?.onFetch(
447 context as FetchContext<TQueryFnData, TError, TData, TQueryKey>,
448 this as unknown as Query,
449 )
450β
451 // Store state in case the current fetch needs to be reverted
452 this.#revertState = this.state
453β
454 // Set to fetching state if not already in it
455 if (
456 this.state.fetchStatus === 'idle' ||
457 this.state.fetchMeta !== context.fetchOptions?.meta
458 ) {
459 this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })
460 }
461β
462 const onError = (error: TError | { silent?: boolean }) => {
463 // Optimistically update state if needed
464 if (!(isCancelledError(error) && error.silent)) {
465 this.#dispatch({
466 type: 'error',
467 error: error as TError,
468 })
469 }
470β
471 if (!isCancelledError(error)) {
472 // Notify cache callback
473 this.#cache.config.onError?.(
474 error as any,
475 this as Query<any, any, any, any>,
476 )
477 this.#cache.config.onSettled?.(
478 this.state.data,
479 error as any,
480 this as Query<any, any, any, any>,
481 )
482 }
483β
484 // Schedule query gc after fetching
485 this.scheduleGc()
486 }
487β
488 // Try to fetch the data
489 this.#retryer = createRetryer({
490 initialPromise: fetchOptions?.initialPromise as
491 | Promise<TData>
492 | undefined,
493 fn: context.fetchFn as () => Promise<TData>,
494 abort: abortController.abort.bind(abortController),
495 onSuccess: (data) => {
496 if (data === undefined) {
497 if (process.env.NODE_ENV !== 'production') {
498 console.error(
499 `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,
500 )
501 }
502 onError(new Error(`${this.queryHash} data is undefined`) as any)
503 return
504 }
505β
506 try {
507 this.setData(data)
508 } catch (error) {
509 onError(error as TError)
510 return
511 }
512β
513 // Notify cache callback
514 this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)
515 this.#cache.config.onSettled?.(
516 data,
517 this.state.error as any,
518 this as Query<any, any, any, any>,
519 )
520β
521 // Schedule query gc after fetching
522 this.scheduleGc()
523 },
524 onError,
525 onFail: (failureCount, error) => {
526 this.#dispatch({ type: 'failed', failureCount, error })
527 },
528 onPause: () => {
529 this.#dispatch({ type: 'pause' })
530 },
531 onContinue: () => {
532 this.#dispatch({ type: 'continue' })
533 },
534 retry: context.options.retry,
535 retryDelay: context.options.retryDelay,
536 networkMode: context.options.networkMode,
537 canRun: () => true,
538 })
539β
540 return this.#retryer.start()
541 }
542β
543 #dispatch(action: Action<TData, TError>): void {
544 const reducer = (
545 state: QueryState<TData, TError>,
546 ): QueryState<TData, TError> => {
547 switch (action.type) {
548 case 'failed':
549 return {
550 ...state,
551 fetchFailureCount: action.failureCount,
552 fetchFailureReason: action.error,
553 }
554 case 'pause':
555 return {
556 ...state,
557 fetchStatus: 'paused',
558 }
559 case 'continue':
560 return {
561 ...state,
562 fetchStatus: 'fetching',
563 }
564 case 'fetch':
565 return {
566 ...state,
567 ...fetchState(state.data, this.options),
568 fetchMeta: action.meta ?? null,
569 }
570 case 'success':
571 return {
572 ...state,
573 data: action.data,
574 dataUpdateCount: state.dataUpdateCount + 1,
575 dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),
576 error: null,
577 isInvalidated: false,
578 status: 'success',
579 ...(!action.manual && {
580 fetchStatus: 'idle',
581 fetchFailureCount: 0,
582 fetchFailureReason: null,
583 }),
584 }
585 case 'error':
586 const error = action.error
587β
588 if (isCancelledError(error) && error.revert && this.#revertState) {
589 return { ...this.#revertState, fetchStatus: 'idle' }
590 }
591β
592 return {
593 ...state,
594 error,
595 errorUpdateCount: state.errorUpdateCount + 1,
596 errorUpdatedAt: Date.now(),
597 fetchFailureCount: state.fetchFailureCount + 1,
598 fetchFailureReason: error,
599 fetchStatus: 'idle',
600 status: 'error',
601 }
602 case 'invalidate':
603 return {
604 ...state,
605 isInvalidated: true,
606 }
607 case 'setState':
608 return {
609 ...state,
610 ...action.state,
611 }
612 }
613 }
614β
615 this.state = reducer(this.state)
616β
617 notifyManager.batch(() => {
618 this.observers.forEach((observer) => {
619 observer.onQueryUpdate()
620 })
621β
622 this.#cache.notify({ query: this, type: 'updated', action })
623 })
624 }
625}
626β
627export function fetchState<
628 TQueryFnData,
629 TError,
630 TData,
631 TQueryKey extends QueryKey,
632>(
633 data: TData | undefined,
634 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
635) {
636 return {
637 fetchFailureCount: 0,
638 fetchFailureReason: null,
639 fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',
640 ...(data === undefined &&
641 ({
642 error: null,
643 status: 'pending',
644 } as const)),
645 } as const
646}
647β
648function getDefaultState<
649 TQueryFnData,
650 TError,
651 TData,
652 TQueryKey extends QueryKey,
653>(
654 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
655): QueryState<TData, TError> {
656 const data =
657 typeof options.initialData === 'function'
658 ? (options.initialData as InitialDataFunction<TData>)()
659 : options.initialData
660β
661 const hasData = data !== undefined
662β
663 const initialDataUpdatedAt = hasData
664 ? typeof options.initialDataUpdatedAt === 'function'
665 ? (options.initialDataUpdatedAt as () => number | undefined)()
666 : options.initialDataUpdatedAt
667 : 0
668β
669 return {
670 data,
671 dataUpdateCount: 0,
672 dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,
673 error: null,
674 errorUpdateCount: 0,
675 errorUpdatedAt: 0,
676 fetchFailureCount: 0,
677 fetchFailureReason: null,
678 fetchMeta: null,
679 isInvalidated: false,
680 status: hasData ? 'success' : 'pending',
681 fetchStatus: 'idle',
682 }
683}