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