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

query.ts

623 lines16.0 KB

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