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