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

query.ts

689 lines17.5 KB

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