Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

query.ts

638 lines15.8 KB

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