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