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

query.ts

627 lines16.2 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>
37 meta: QueryMeta | undefined
39​
40export interface QueryState<TData = unknown, TError = unknown> {
41 data: TData | undefined
42 dataUpdateCount: number
43 dataUpdatedAt: number
44 error: TError | null
45 errorUpdateCount: number
46 errorUpdatedAt: number
47 fetchFailureCount: number
48 fetchFailureReason: TError | null
49 fetchMeta: any
50 isInvalidated: boolean
51 status: QueryStatus
52 fetchStatus: FetchStatus
54​
55export interface FetchContext<
56 TQueryFnData,
57 TError,
58 TData,
59 TQueryKey extends QueryKey = QueryKey,
60> {
61 fetchFn: () => unknown | Promise<unknown>
62 fetchOptions?: FetchOptions
63 signal?: AbortSignal
64 options: QueryOptions<TQueryFnData, TError, TData, any>
65 queryKey: TQueryKey
66 state: QueryState<TData, TError>
67 meta: QueryMeta | undefined
69​
70export interface QueryBehavior<
71 TQueryFnData = unknown,
72 TError = unknown,
73 TData = TQueryFnData,
74 TQueryKey extends QueryKey = QueryKey,
75> {
76 onFetch: (
77 context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,
78 ) => void
80​
81export interface FetchOptions {
82 cancelRefetch?: boolean
83 meta?: any
85​
86interface FailedAction<TError> {
87 type: 'failed'
88 failureCount: number
89 error: TError
91​
92interface FetchAction {
93 type: 'fetch'
94 meta?: any
96​
97interface SuccessAction<TData> {
98 data: TData | undefined
99 type: 'success'
100 dataUpdatedAt?: number
101 manual?: boolean
103​
104interface ErrorAction<TError> {
105 type: 'error'
106 error: TError
108​
109interface InvalidateAction {
110 type: 'invalidate'
112​
113interface PauseAction {
114 type: 'pause'
116​
117interface ContinueAction {
118 type: 'continue'
120​
121interface SetStateAction<TData, TError> {
122 type: 'setState'
123 state: QueryState<TData, TError>
124 setStateOptions?: SetStateOptions
126​
127export type Action<TData, TError> =
128 | ContinueAction
129 | ErrorAction<TError>
130 | FailedAction<TError>
131 | FetchAction
132 | InvalidateAction
133 | PauseAction
134 | SetStateAction<TData, TError>
135 | SuccessAction<TData>
136​
137export interface SetStateOptions {
138 meta?: any
140​
141// CLASS
142​
143export class Query<
144 TQueryFnData = unknown,
145 TError = unknown,
146 TData = TQueryFnData,
147 TQueryKey extends QueryKey = QueryKey,
148> extends Removable {
149 queryKey: TQueryKey
150 queryHash: string
151 options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
152 initialState: QueryState<TData, TError>
153 revertState?: QueryState<TData, TError>
154 state: QueryState<TData, TError>
155 meta: QueryMeta | undefined
156 isFetchingOptimistic?: boolean
157​
158 private cache: QueryCache
159 private logger: Logger
160 private promise?: Promise<TData>
161 private retryer?: Retryer<TData>
162 private observers: QueryObserver<any, any, any, any, any>[]
163 private defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
164 private abortSignalConsumed: boolean
165​
166 constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {
167 super()
168​
169 this.abortSignalConsumed = false
170 this.defaultOptions = config.defaultOptions
171 this.setOptions(config.options)
172 this.observers = []
173 this.cache = config.cache
174 this.logger = config.logger || defaultLogger
175 this.queryKey = config.queryKey
176 this.queryHash = config.queryHash
177 this.initialState = config.state || getDefaultState(this.options)
178 this.state = this.initialState
179 this.meta = config.meta
180 }
181​
182 private setOptions(
183 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
184 ): void {
185 this.options = { ...this.defaultOptions, ...options }
186​
187 this.meta = options?.meta
188​
189 this.updateCacheTime(this.options.cacheTime)
190 }
191​
192 protected optionalRemove() {
193 if (!this.observers.length && this.state.fetchStatus === 'idle') {
194 this.cache.remove(this)
195 }
196 }
197​
198 setData(
199 newData: TData,
200 options?: SetDataOptions & { manual: boolean },
201 ): TData {
202 const data = replaceData(this.state.data, newData, this.options)
203​
204 // Set data and mark it as cached
205 this.dispatch({
206 data,
207 type: 'success',
208 dataUpdatedAt: options?.updatedAt,
209 manual: options?.manual,
210 })
211​
212 return data
213 }
214​
215 setState(
216 state: QueryState<TData, TError>,
217 setStateOptions?: SetStateOptions,
218 ): void {
219 this.dispatch({ type: 'setState', state, setStateOptions })
220 }
221​
222 cancel(options?: CancelOptions): Promise<void> {
223 const promise = this.promise
224 this.retryer?.cancel(options)
225 return promise ? promise.then(noop).catch(noop) : Promise.resolve()
226 }
227​
228 destroy(): void {
229 super.destroy()
230​
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 isDisabled(): boolean {
244 return this.getObserversCount() > 0 && !this.isActive()
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({ cancelRefetch: false })
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({ cancelRefetch: false })
279 }
280​
281 // Continue fetch if currently paused
282 this.retryer?.continue()
283 }
284​
285 addObserver(observer: QueryObserver<any, 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({ type: 'observerAdded', query: this, observer })
293 }
294 }
295​
296 removeObserver(observer: QueryObserver<any, 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.abortSignalConsumed) {
305 this.retryer.cancel({ revert: true })
306 } else {
307 this.retryer.cancelRetry()
308 }
309 }
310​
311 this.scheduleGc()
312 }
313​
314 this.cache.notify({ type: 'observerRemoved', query: this, observer })
315 }
316 }
317​
318 getObserversCount(): number {
319 return this.observers.length
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, TQueryKey>,
330 fetchOptions?: FetchOptions,
331 ): Promise<TData> {
332 if (this.state.fetchStatus !== 'idle') {
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 // make sure that retries that were potentially cancelled due to unmounts can continue
338 this.retryer?.continueRetry()
339 // Return current promise if we are already fetching
340 return this.promise
341 }
342 }
343​
344 // Update config if passed, otherwise the config from the last execution is used
345 if (options) {
346 this.setOptions(options)
347 }
348​
349 // Use the options from the first observer with a query function if no function is found.
350 // This can happen when the query is hydrated or created with setQueryData.
351 if (!this.options.queryFn) {
352 const observer = this.observers.find((x) => x.options.queryFn)
353 if (observer) {
354 this.setOptions(observer.options)
355 }
356 }
357​
358 if (!Array.isArray(this.options.queryKey)) {
359 if (process.env.NODE_ENV !== 'production') {
360 this.logger.error(
361 `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']`,
362 )
363 }
364 }
365​
366 const abortController = getAbortController()
367​
368 // Create query function context
369 const queryFnContext: QueryFunctionContext<TQueryKey> = {
370 queryKey: this.queryKey,
371 pageParam: undefined,
372 meta: this.meta,
373 }
374​
375 // Adds an enumerable signal property to the object that
376 // which sets abortSignalConsumed to true when the signal
377 // is read.
378 const addSignalProperty = (object: unknown) => {
379 Object.defineProperty(object, 'signal', {
380 enumerable: true,
381 get: () => {
382 if (abortController) {
383 this.abortSignalConsumed = true
384 return abortController.signal
385 }
386 return undefined
387 },
388 })
389 }
390​
391 addSignalProperty(queryFnContext)
392​
393 // Create fetch function
394 const fetchFn = () => {
395 if (!this.options.queryFn) {
396 return Promise.reject('Missing queryFn')
397 }
398 this.abortSignalConsumed = false
399 return this.options.queryFn(queryFnContext)
400 }
401​
402 // Trigger behavior hook
403 const context: FetchContext<TQueryFnData, TError, TData, TQueryKey> = {
404 fetchOptions,
405 options: this.options,
406 queryKey: this.queryKey,
407 state: this.state,
408 fetchFn,
409 meta: this.meta,
410 }
411​
412 addSignalProperty(context)
413​
414 this.options.behavior?.onFetch(context)
415​
416 // Store state in case the current fetch needs to be reverted
417 this.revertState = this.state
418​
419 // Set to fetching state if not already in it
420 if (
421 this.state.fetchStatus === 'idle' ||
422 this.state.fetchMeta !== context.fetchOptions?.meta
423 ) {
424 this.dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })
425 }
426​
427 const onError = (error: TError | { silent?: boolean }) => {
428 // Optimistically update state if needed
429 if (!(isCancelledError(error) && error.silent)) {
430 this.dispatch({
431 type: 'error',
432 error: error as TError,
433 })
434 }
435​
436 if (!isCancelledError(error)) {
437 // Notify cache callback
438 this.cache.config.onError?.(error, this as Query<any, any, any, any>)
439​
440 if (process.env.NODE_ENV !== 'production') {
441 this.logger.error(error)
442 }
443 }
444​
445 if (!this.isFetchingOptimistic) {
446 // Schedule query gc after fetching
447 this.scheduleGc()
448 }
449 this.isFetchingOptimistic = false
450 }
451​
452 // Try to fetch the data
453 this.retryer = createRetryer({
454 fn: context.fetchFn as () => TData,
455 abort: abortController?.abort.bind(abortController),
456 onSuccess: (data) => {
457 if (typeof data === 'undefined') {
458 if (process.env.NODE_ENV !== 'production') {
459 this.logger.error(
460 `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,
461 )
462 }
463 onError(new Error('undefined') as any)
464 return
465 }
466​
467 this.setData(data as TData)
468​
469 // Notify cache callback
470 this.cache.config.onSuccess?.(data, this as Query<any, any, any, any>)
471​
472 if (!this.isFetchingOptimistic) {
473 // Schedule query gc after fetching
474 this.scheduleGc()
475 }
476 this.isFetchingOptimistic = false
477 },
478 onError,
479 onFail: (failureCount, error) => {
480 this.dispatch({ type: 'failed', failureCount, error })
481 },
482 onPause: () => {
483 this.dispatch({ type: 'pause' })
484 },
485 onContinue: () => {
486 this.dispatch({ type: 'continue' })
487 },
488 retry: context.options.retry,
489 retryDelay: context.options.retryDelay,
490 networkMode: context.options.networkMode,
491 })
492​
493 this.promise = this.retryer.promise
494​
495 return this.promise
496 }
497​
498 private dispatch(action: Action<TData, TError>): void {
499 const reducer = (
500 state: QueryState<TData, TError>,
501 ): QueryState<TData, TError> => {
502 switch (action.type) {
503 case 'failed':
504 return {
505 ...state,
506 fetchFailureCount: action.failureCount,
507 fetchFailureReason: action.error,
508 }
509 case 'pause':
510 return {
511 ...state,
512 fetchStatus: 'paused',
513 }
514 case 'continue':
515 return {
516 ...state,
517 fetchStatus: 'fetching',
518 }
519 case 'fetch':
520 return {
521 ...state,
522 fetchFailureCount: 0,
523 fetchFailureReason: null,
524 fetchMeta: action.meta ?? null,
525 fetchStatus: canFetch(this.options.networkMode)
526 ? 'fetching'
527 : 'paused',
528 ...(!state.dataUpdatedAt && {
529 error: null,
530 status: 'loading',
531 }),
532 }
533 case 'success':
534 return {
535 ...state,
536 data: action.data,
537 dataUpdateCount: state.dataUpdateCount + 1,
538 dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),
539 error: null,
540 isInvalidated: false,
541 status: 'success',
542 ...(!action.manual && {
543 fetchStatus: 'idle',
544 fetchFailureCount: 0,
545 fetchFailureReason: null,
546 }),
547 }
548 case 'error':
549 const error = action.error as unknown
550​
551 if (isCancelledError(error) && error.revert && this.revertState) {
552 return { ...this.revertState }
553 }
554​
555 return {
556 ...state,
557 error: error as TError,
558 errorUpdateCount: state.errorUpdateCount + 1,
559 errorUpdatedAt: Date.now(),
560 fetchFailureCount: state.fetchFailureCount + 1,
561 fetchFailureReason: error as TError,
562 fetchStatus: 'idle',
563 status: 'error',
564 }
565 case 'invalidate':
566 return {
567 ...state,
568 isInvalidated: true,
569 }
570 case 'setState':
571 return {
572 ...state,
573 ...action.state,
574 }
575 }
576 }
577​
578 this.state = reducer(this.state)
579​
580 notifyManager.batch(() => {
581 this.observers.forEach((observer) => {
582 observer.onQueryUpdate(action)
583 })
584​
585 this.cache.notify({ query: this, type: 'updated', action })
586 })
587 }
589​
590function getDefaultState<
591 TQueryFnData,
592 TError,
593 TData,
594 TQueryKey extends QueryKey,
595>(
596 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
597): QueryState<TData, TError> {
598 const data =
599 typeof options.initialData === 'function'
600 ? (options.initialData as InitialDataFunction<TData>)()
601 : options.initialData
602​
603 const hasInitialData = typeof options.initialData !== 'undefined'
604​
605 const initialDataUpdatedAt = hasInitialData
606 ? typeof options.initialDataUpdatedAt === 'function'
607 ? (options.initialDataUpdatedAt as () => number | undefined)()
608 : options.initialDataUpdatedAt
609 : 0
610​
611 const hasData = typeof data !== 'undefined'
612​
613 return {
614 data,
615 dataUpdateCount: 0,
616 dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
617 error: null,
618 errorUpdateCount: 0,
619 errorUpdatedAt: 0,
620 fetchFailureCount: 0,
621 fetchFailureReason: null,
622 fetchMeta: null,
623 isInvalidated: false,
624 status: hasData ? 'success' : 'loading',
625 fetchStatus: 'idle',
626 }