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

query.ts

605 lines14.8 KB

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
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
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
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
81​
82export interface FetchOptions {
83 cancelRefetch?: boolean
84 meta?: any
86​
87export interface SetDataOptions {
88 updatedAt?: number
90​
91interface FailedAction {
92 type: 'failed'
94​
95interface FetchAction {
96 type: 'fetch'
97 meta?: any
99​
100interface SuccessAction<TData> {
101 data: TData | undefined
102 type: 'success'
103 dataUpdatedAt?: number
105​
106interface ErrorAction<TError> {
107 type: 'error'
108 error: TError
110​
111interface InvalidateAction {
112 type: 'invalidate'
114​
115interface PauseAction {
116 type: 'pause'
118​
119interface ContinueAction {
120 type: 'continue'
122​
123interface SetStateAction<TData, TError> {
124 type: 'setState'
125 state: QueryState<TData, TError>
126 setStateOptions?: SetStateOptions
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
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 }