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