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: 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: 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β
438 if (process.env.NODE_ENV !== 'production') {
439 this.logger.error(error)
440 }
441 }
442β
443 if (!this.isFetchingOptimistic) {
444 // Schedule query gc after fetching
445 this.scheduleGc()
446 }
447 this.isFetchingOptimistic = false
448 }
449β
450 // Try to fetch the data
451 this.retryer = createRetryer({
452 fn: context.fetchFn as () => TData,
453 abort: abortController?.abort.bind(abortController),
454 onSuccess: (data) => {
455 if (typeof data === 'undefined') {
456 if (process.env.NODE_ENV !== 'production') {
457 this.logger.error(
458 `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,
459 )
460 }
461 onError(new Error('undefined') as any)
462 return
463 }
464β
465 this.setData(data as TData)
466β
467 // Notify cache callback
468 this.cache.config.onSuccess?.(data, this as Query<any, any, any, any>)
469β
470 if (!this.isFetchingOptimistic) {
471 // Schedule query gc after fetching
472 this.scheduleGc()
473 }
474 this.isFetchingOptimistic = false
475 },
476 onError,
477 onFail: (failureCount, error) => {
478 this.dispatch({ type: 'failed', failureCount, error })
479 },
480 onPause: () => {
481 this.dispatch({ type: 'pause' })
482 },
483 onContinue: () => {
484 this.dispatch({ type: 'continue' })
485 },
486 retry: context.options.retry,
487 retryDelay: context.options.retryDelay,
488 networkMode: context.options.networkMode,
489 })
490β
491 this.promise = this.retryer.promise
492β
493 return this.promise
494 }
495β
496 private dispatch(action: Action<TData, TError>): void {
497 const reducer = (
498 state: QueryState<TData, TError>,
499 ): QueryState<TData, TError> => {
500 switch (action.type) {
501 case 'failed':
502 return {
503 ...state,
504 fetchFailureCount: action.failureCount,
505 fetchFailureReason: action.error,
506 }
507 case 'pause':
508 return {
509 ...state,
510 fetchStatus: 'paused',
511 }
512 case 'continue':
513 return {
514 ...state,
515 fetchStatus: 'fetching',
516 }
517 case 'fetch':
518 return {
519 ...state,
520 fetchFailureCount: 0,
521 fetchFailureReason: null,
522 fetchMeta: action.meta ?? null,
523 fetchStatus: canFetch(this.options.networkMode)
524 ? 'fetching'
525 : 'paused',
526 ...(!state.dataUpdatedAt && {
527 error: null,
528 status: 'loading',
529 }),
530 }
531 case 'success':
532 return {
533 ...state,
534 data: action.data,
535 dataUpdateCount: state.dataUpdateCount + 1,
536 dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),
537 error: null,
538 isInvalidated: false,
539 status: 'success',
540 ...(!action.manual && {
541 fetchStatus: 'idle',
542 fetchFailureCount: 0,
543 fetchFailureReason: null,
544 }),
545 }
546 case 'error':
547 const error = action.error as unknown
548β
549 if (isCancelledError(error) && error.revert && this.revertState) {
550 return { ...this.revertState }
551 }
552β
553 return {
554 ...state,
555 error: error as TError,
556 errorUpdateCount: state.errorUpdateCount + 1,
557 errorUpdatedAt: Date.now(),
558 fetchFailureCount: state.fetchFailureCount + 1,
559 fetchFailureReason: error as TError,
560 fetchStatus: 'idle',
561 status: 'error',
562 }
563 case 'invalidate':
564 return {
565 ...state,
566 isInvalidated: true,
567 }
568 case 'setState':
569 return {
570 ...state,
571 ...action.state,
572 }
573 }
574 }
575β
576 this.state = reducer(this.state)
577β
578 notifyManager.batch(() => {
579 this.observers.forEach((observer) => {
580 observer.onQueryUpdate(action)
581 })
582β
583 this.cache.notify({ query: this, type: 'updated', action })
584 })
585 }
586}
587β
588function getDefaultState<
589 TQueryFnData,
590 TError,
591 TData,
592 TQueryKey extends QueryKey,
593>(
594 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
595): QueryState<TData, TError> {
596 const data =
597 typeof options.initialData === 'function'
598 ? (options.initialData as InitialDataFunction<TData>)()
599 : options.initialData
600β
601 const hasData = typeof data !== 'undefined'
602β
603 const initialDataUpdatedAt = hasData
604 ? typeof options.initialDataUpdatedAt === 'function'
605 ? (options.initialDataUpdatedAt as () => number | undefined)()
606 : options.initialDataUpdatedAt
607 : 0
608β
609 return {
610 data,
611 dataUpdateCount: 0,
612 dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
613 error: null,
614 errorUpdateCount: 0,
615 errorUpdatedAt: 0,
616 fetchFailureCount: 0,
617 fetchFailureReason: null,
618 fetchMeta: null,
619 isInvalidated: false,
620 status: hasData ? 'success' : 'loading',
621 fetchStatus: 'idle',
622 }
623}