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