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