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

query.ts

646 lines16.7 KB

1import { noop, replaceData, timeUntilStale } from './utils'
2import { notifyManager } from './notifyManager'
3import { canFetch, createRetryer, isCancelledError } from './retryer'
4import { Removable } from './removable'
5import type {
6 CancelOptions,
7 DefaultError,
8 FetchStatus,
9 InitialDataFunction,
10 QueryFunctionContext,
11 QueryKey,
12 QueryMeta,
13 QueryOptions,
14 QueryStatus,
15 SetDataOptions,
16} from './types'
17import type { QueryCache } from './queryCache'
18import type { QueryObserver } from './queryObserver'
19import type { Retryer } from './retryer'
20​
21// TYPES
22​
23interface QueryConfig<
24 TQueryFnData,
25 TError,
26 TData,
27 TQueryKey extends QueryKey = QueryKey,
28> {
29 cache: QueryCache
30 queryKey: TQueryKey
31 queryHash: string
32 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
33 defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
34 state?: QueryState<TData, TError>
36​
37export interface QueryState<TData = unknown, TError = DefaultError> {
38 data: TData | undefined
39 dataUpdateCount: number
40 dataUpdatedAt: number
41 error: TError | null
42 errorUpdateCount: number
43 errorUpdatedAt: number
44 fetchFailureCount: number
45 fetchFailureReason: TError | null
46 fetchMeta: FetchMeta | null
47 isInvalidated: boolean
48 status: QueryStatus
49 fetchStatus: FetchStatus
51​
52export interface FetchContext<
53 TQueryFnData,
54 TError,
55 TData,
56 TQueryKey extends QueryKey = QueryKey,
57> {
58 fetchFn: () => unknown | Promise<unknown>
59 fetchOptions?: FetchOptions
60 signal: AbortSignal
61 options: QueryOptions<TQueryFnData, TError, TData, any>
62 queryKey: TQueryKey
63 state: QueryState<TData, TError>
65​
66export interface QueryBehavior<
67 TQueryFnData = unknown,
68 TError = DefaultError,
69 TData = TQueryFnData,
70 TQueryKey extends QueryKey = QueryKey,
71> {
72 onFetch: (
73 context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,
74 query: Query,
75 ) => void
77​
78export type FetchDirection = 'forward' | 'backward'
79​
80export interface FetchMeta {
81 fetchMore?: { direction: FetchDirection }
83​
84export interface FetchOptions {
85 cancelRefetch?: boolean
86 meta?: FetchMeta
88​
89interface FailedAction<TError> {
90 type: 'failed'
91 failureCount: number
92 error: TError
94​
95interface FetchAction {
96 type: 'fetch'
97 meta?: FetchMeta
99​
100interface SuccessAction<TData> {
101 data: TData | undefined
102 type: 'success'
103 dataUpdatedAt?: number
104 manual?: boolean
106​
107interface ErrorAction<TError> {
108 type: 'error'
109 error: TError
111​
112interface InvalidateAction {
113 type: 'invalidate'
115​
116interface PauseAction {
117 type: 'pause'
119​
120interface ContinueAction {
121 type: 'continue'
123​
124interface SetStateAction<TData, TError> {
125 type: 'setState'
126 state: Partial<QueryState<TData, TError>>
127 setStateOptions?: SetStateOptions
129​
130export type Action<TData, TError> =
131 | ContinueAction
132 | ErrorAction<TError>
133 | FailedAction<TError>
134 | FetchAction
135 | InvalidateAction
136 | PauseAction
137 | SetStateAction<TData, TError>
138 | SuccessAction<TData>
139​
140export interface SetStateOptions {
141 meta?: any
143​
144// CLASS
145​
146export class Query<
147 TQueryFnData = unknown,
148 TError = DefaultError,
149 TData = TQueryFnData,
150 TQueryKey extends QueryKey = QueryKey,
151> extends Removable {
152 queryKey: TQueryKey
153 queryHash: string
154 options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
155 state: QueryState<TData, TError>
156 isFetchingOptimistic?: boolean
157​
158 #initialState: QueryState<TData, TError>
159 #revertState?: QueryState<TData, TError>
160 #cache: QueryCache
161 #promise?: Promise<TData>
162 #retryer?: Retryer<TData>
163 #observers: Array<QueryObserver<any, any, any, any, any>>
164 #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
165 #abortSignalConsumed: boolean
166​
167 constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {
168 super()
169​
170 this.#abortSignalConsumed = 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 || getDefaultState(this.options)
178 this.state = this.#initialState
179 this.scheduleGc()
180 }
181 get meta(): QueryMeta | undefined {
182 return this.options.meta
183 }
184​
185 #setOptions(
186 options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
187 ): void {
188 this.options = { ...this.#defaultOptions, ...options }
189​
190 this.updateGcTime(this.options.gcTime)
191 }
192​
193 protected optionalRemove() {
194 if (!this.#observers.length && this.state.fetchStatus === 'idle') {
195 this.#cache.remove(this)
196 }
197 }
198​
199 setData(
200 newData: TData,
201 options?: SetDataOptions & { manual: boolean },
202 ): TData {
203 const data = replaceData(this.state.data, newData, this.options)
204​
205 // Set data and mark it as cached
206 this.#dispatch({
207 data,
208 type: 'success',
209 dataUpdatedAt: options?.updatedAt,
210 manual: options?.manual,
211 })
212​
213 return data
214 }
215​
216 setState(
217 state: Partial<QueryState<TData, TError>>,
218 setStateOptions?: SetStateOptions,
219 ): void {
220 this.#dispatch({ type: 'setState', state, setStateOptions })
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 super.destroy()
231​
232 this.cancel({ silent: true })
233 }
234​
235 reset(): void {
236 this.destroy()
237 this.setState(this.#initialState)
238 }
239​
240 isActive(): boolean {
241 return this.#observers.some(
242 (observer) => observer.options.enabled !== false,
243 )
244 }
245​
246 isDisabled(): boolean {
247 return this.getObserversCount() > 0 && !this.isActive()
248 }
249​
250 isStale(): boolean {
251 return (
252 this.state.isInvalidated ||
253 !this.state.dataUpdatedAt ||
254 this.#observers.some((observer) => observer.getCurrentResult().isStale)
255 )
256 }
257​
258 isStaleByTime(staleTime = 0): boolean {
259 return (
260 this.state.isInvalidated ||
261 !this.state.dataUpdatedAt ||
262 !timeUntilStale(this.state.dataUpdatedAt, staleTime)
263 )
264 }
265​
266 onFocus(): void {
267 const observer = this.#observers.find((x) => x.shouldFetchOnWindowFocus())
268​
269 observer?.refetch({ cancelRefetch: false })
270​
271 // Continue fetch if currently paused
272 this.#retryer?.continue()
273 }
274​
275 onOnline(): void {
276 const observer = this.#observers.find((x) => x.shouldFetchOnReconnect())
277​
278 observer?.refetch({ cancelRefetch: false })
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.includes(observer)) {
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.includes(observer)) {
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 (process.env.NODE_ENV !== 'production') {
358 if (!Array.isArray(this.options.queryKey)) {
359 console.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 = new AbortController()
366​
367 // Create query function context
368 const queryFnContext: Omit<QueryFunctionContext<TQueryKey>, 'signal'> = {
369 queryKey: this.queryKey,
370 meta: this.meta,
371 }
372​
373 // Adds an enumerable signal property to the object that
374 // which sets abortSignalConsumed to true when the signal
375 // is read.
376 const addSignalProperty = (object: unknown) => {
377 Object.defineProperty(object, 'signal', {
378 enumerable: true,
379 get: () => {
380 this.#abortSignalConsumed = true
381 return abortController.signal
382 },
383 })
384 }
385​
386 addSignalProperty(queryFnContext)
387​
388 // Create fetch function
389 const fetchFn = () => {
390 if (!this.options.queryFn) {
391 return Promise.reject(
392 new Error(`Missing queryFn: '${this.options.queryHash}'`),
393 )
394 }
395 this.#abortSignalConsumed = false
396 if (this.options.persister) {
397 return this.options.persister(
398 this.options.queryFn,
399 queryFnContext as QueryFunctionContext<TQueryKey>,
400 this as unknown as Query,
401 )
402 }
403​
404 return this.options.queryFn(
405 queryFnContext as QueryFunctionContext<TQueryKey>,
406 )
407 }
408​
409 // Trigger behavior hook
410 const context: Omit<
411 FetchContext<TQueryFnData, TError, TData, TQueryKey>,
412 'signal'
413 > = {
414 fetchOptions,
415 options: this.options,
416 queryKey: this.queryKey,
417 state: this.state,
418 fetchFn,
419 }
420​
421 addSignalProperty(context)
422​
423 this.options.behavior?.onFetch(
424 context as FetchContext<TQueryFnData, TError, TData, TQueryKey>,
425 this as unknown as Query,
426 )
427​
428 // Store state in case the current fetch needs to be reverted
429 this.#revertState = this.state
430​
431 // Set to fetching state if not already in it
432 if (
433 this.state.fetchStatus === 'idle' ||
434 this.state.fetchMeta !== context.fetchOptions?.meta
435 ) {
436 this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })
437 }
438​
439 const onError = (error: TError | { silent?: boolean }) => {
440 // Optimistically update state if needed
441 if (!(isCancelledError(error) && error.silent)) {
442 this.#dispatch({
443 type: 'error',
444 error: error as TError,
445 })
446 }
447​
448 if (!isCancelledError(error)) {
449 // Notify cache callback
450 this.#cache.config.onError?.(
451 error as any,
452 this as Query<any, any, any, any>,
453 )
454 this.#cache.config.onSettled?.(
455 this.state.data,
456 error as any,
457 this as Query<any, any, any, any>,
458 )
459 }
460​
461 if (!this.isFetchingOptimistic) {
462 // Schedule query gc after fetching
463 this.scheduleGc()
464 }
465 this.isFetchingOptimistic = false
466 }
467​
468 // Try to fetch the data
469 this.#retryer = createRetryer({
470 fn: context.fetchFn as () => Promise<TData>,
471 abort: abortController.abort.bind(abortController),
472 onSuccess: (data) => {
473 if (typeof data === 'undefined') {
474 if (process.env.NODE_ENV !== 'production') {
475 console.error(
476 `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,
477 )
478 }
479 onError(new Error(`${this.queryHash} data is undefined`) as any)
480 return
481 }
482​
483 this.setData(data)
484​
485 // Notify cache callback
486 this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)
487 this.#cache.config.onSettled?.(
488 data,
489 this.state.error as any,
490 this as Query<any, any, any, any>,
491 )
492​
493 if (!this.isFetchingOptimistic) {
494 // Schedule query gc after fetching
495 this.scheduleGc()
496 }
497 this.isFetchingOptimistic = false
498 },
499 onError,
500 onFail: (failureCount, error) => {
501 this.#dispatch({ type: 'failed', failureCount, error })
502 },
503 onPause: () => {
504 this.#dispatch({ type: 'pause' })
505 },
506 onContinue: () => {
507 this.#dispatch({ type: 'continue' })
508 },
509 retry: context.options.retry,
510 retryDelay: context.options.retryDelay,
511 networkMode: context.options.networkMode,
512 })
513​
514 this.#promise = this.#retryer.promise
515​
516 return this.#promise
517 }
518​
519 #dispatch(action: Action<TData, TError>): void {
520 const reducer = (
521 state: QueryState<TData, TError>,
522 ): QueryState<TData, TError> => {
523 switch (action.type) {
524 case 'failed':
525 return {
526 ...state,
527 fetchFailureCount: action.failureCount,
528 fetchFailureReason: action.error,
529 }
530 case 'pause':
531 return {
532 ...state,
533 fetchStatus: 'paused',
534 }
535 case 'continue':
536 return {
537 ...state,
538 fetchStatus: 'fetching',
539 }
540 case 'fetch':
541 return {
542 ...state,
543 fetchFailureCount: 0,
544 fetchFailureReason: null,
545 fetchMeta: action.meta ?? null,
546 fetchStatus: canFetch(this.options.networkMode)
547 ? 'fetching'
548 : 'paused',
549 ...(!state.dataUpdatedAt && {
550 error: null,
551 status: 'pending',
552 }),
553 }
554 case 'success':
555 return {
556 ...state,
557 data: action.data,
558 dataUpdateCount: state.dataUpdateCount + 1,
559 dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),
560 error: null,
561 isInvalidated: false,
562 status: 'success',
563 ...(!action.manual && {
564 fetchStatus: 'idle',
565 fetchFailureCount: 0,
566 fetchFailureReason: null,
567 }),
568 }
569 case 'error':
570 const error = action.error as unknown
571​
572 if (isCancelledError(error) && error.revert && this.#revertState) {
573 return { ...this.#revertState, fetchStatus: 'idle' }
574 }
575​
576 return {
577 ...state,
578 error: error as TError,
579 errorUpdateCount: state.errorUpdateCount + 1,
580 errorUpdatedAt: Date.now(),
581 fetchFailureCount: state.fetchFailureCount + 1,
582 fetchFailureReason: error as TError,
583 fetchStatus: 'idle',
584 status: 'error',
585 }
586 case 'invalidate':
587 return {
588 ...state,
589 isInvalidated: true,
590 }
591 case 'setState':
592 return {
593 ...state,
594 ...action.state,
595 }
596 }
597 }
598​
599 this.state = reducer(this.state)
600​
601 notifyManager.batch(() => {
602 this.#observers.forEach((observer) => {
603 observer.onQueryUpdate()
604 })
605​
606 this.#cache.notify({ query: this, type: 'updated', action })
607 })
608 }
610​
611function getDefaultState<
612 TQueryFnData,
613 TError,
614 TData,
615 TQueryKey extends QueryKey,
616>(
617 options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
618): QueryState<TData, TError> {
619 const data =
620 typeof options.initialData === 'function'
621 ? (options.initialData as InitialDataFunction<TData>)()
622 : options.initialData
623​
624 const hasData = typeof data !== 'undefined'
625​
626 const initialDataUpdatedAt = hasData
627 ? typeof options.initialDataUpdatedAt === 'function'
628 ? (options.initialDataUpdatedAt as () => number | undefined)()
629 : options.initialDataUpdatedAt
630 : 0
631​
632 return {
633 data,
634 dataUpdateCount: 0,
635 dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
636 error: null,
637 errorUpdateCount: 0,
638 errorUpdatedAt: 0,
639 fetchFailureCount: 0,
640 fetchFailureReason: null,
641 fetchMeta: null,
642 isInvalidated: false,
643 status: hasData ? 'success' : 'pending',
644 fetchStatus: 'idle',
645 }