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