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

queryObserver.ts

789 lines21.8 KB

1import { focusManager } from './focusManager'
2import { isServer as isServerEnvironment } from './environmentManager'
3import { notifyManager } from './notifyManager'
4import { fetchState } from './query'
5import { Subscribable } from './subscribable'
6import {
7 isValidTimeout,
8 noop,
9 replaceData,
10 resolveQueryValue,
11 shallowEqualObjects,
12 timeUntilStale,
13} from './utils'
14import { timeoutManager } from './timeoutManager'
15import type { ManagedTimerId } from './timeoutManager'
16import type { FetchOptions, Query, QueryState } from './query'
17import type { QueryClient } from './queryClient'
18import type {
19 DefaultError,
20 DefaultedQueryObserverOptions,
21 PlaceholderDataFunction,
22 QueryKey,
23 QueryObserverBaseResult,
24 QueryObserverOptions,
25 QueryObserverResult,
26 RefetchOptions,
27} from './types'
28​
29type QueryObserverListener<TData, TError> = (
30 result: QueryObserverResult<TData, TError>,
31) => void
32​
33interface ObserverFetchOptions extends FetchOptions {
34 throwOnError?: boolean
36​
37export class QueryObserver<
38 TQueryFnData = unknown,
39 TError = DefaultError,
40 TData = TQueryFnData,
41 TQueryData = TQueryFnData,
42 TQueryKey extends QueryKey = QueryKey,
43> extends Subscribable<QueryObserverListener<TData, TError>> {
44 #client: QueryClient
45 #currentQuery: Query<TQueryFnData, TError, TQueryData, TQueryKey> = undefined!
46 #currentQueryInitialState: QueryState<TQueryData, TError> = undefined!
47 #currentResult: QueryObserverResult<TData, TError> = undefined!
48 #currentResultState?: QueryState<TQueryData, TError>
49 #currentResultOptions?: QueryObserverOptions<
50 TQueryFnData,
51 TError,
52 TData,
53 TQueryData,
54 TQueryKey
55 >
56 #selectError: TError | null
57 #selectFn?: (data: TQueryData) => TData
58 #selectResult?: TData
59 // This property keeps track of the last query with defined data.
60 // It will be used to pass the previous data and query to the placeholder function between renders.
61 #lastQueryWithDefinedData?: Query<TQueryFnData, TError, TQueryData, TQueryKey>
62 #staleTimeoutId?: ManagedTimerId
63 #refetchIntervalId?: ManagedTimerId
64 #currentRefetchInterval?: number | false
65 #trackedProps = new Set<keyof QueryObserverResult>()
66​
67 constructor(
68 client: QueryClient,
69 public options: QueryObserverOptions<
70 TQueryFnData,
71 TError,
72 TData,
73 TQueryData,
74 TQueryKey
75 >,
76 ) {
77 super()
78​
79 this.#client = client
80 this.#selectError = null
81​
82 this.bindMethods()
83 this.setOptions(options)
84 }
85​
86 protected bindMethods(): void {
87 this.refetch = this.refetch.bind(this)
88 }
89​
90 protected onSubscribe(): void {
91 if (this.listeners.size === 1) {
92 this.#currentQuery.addObserver(this)
93​
94 if (shouldFetchOnMount(this.#currentQuery, this.options)) {
95 this.#executeFetch()
96 } else {
97 this.updateResult()
98 }
99​
100 this.#updateTimers()
101 }
102 }
103​
104 protected onUnsubscribe(): void {
105 if (!this.hasListeners()) {
106 this.destroy()
107 }
108 }
109​
110 shouldFetchOnReconnect(): boolean {
111 return shouldFetchOn(
112 this.#currentQuery,
113 this.options,
114 this.options.refetchOnReconnect,
115 )
116 }
117​
118 shouldFetchOnWindowFocus(): boolean {
119 return shouldFetchOn(
120 this.#currentQuery,
121 this.options,
122 this.options.refetchOnWindowFocus,
123 )
124 }
125​
126 destroy(): void {
127 this.listeners = new Set()
128 this.#clearStaleTimeout()
129 this.#clearRefetchInterval()
130 this.#currentQuery.removeObserver(this)
131 }
132​
133 setOptions(
134 options: QueryObserverOptions<
135 TQueryFnData,
136 TError,
137 TData,
138 TQueryData,
139 TQueryKey
140 >,
141 ): void {
142 const prevOptions = this.options
143 const prevQuery = this.#currentQuery
144​
145 this.options = this.#client.defaultQueryOptions(options)
146​
147 if (
148 this.options.enabled !== undefined &&
149 typeof this.options.enabled !== 'boolean' &&
150 typeof this.options.enabled !== 'function' &&
151 typeof resolveQueryValue(this.options.enabled, this.#currentQuery) !==
152 'boolean'
153 ) {
154 throw new Error(
155 'Expected enabled to be a boolean or a callback that returns a boolean',
156 )
157 }
158​
159 this.#updateQuery()
160 this.#currentQuery.setOptions(this.options)
161​
162 if (
163 prevOptions._defaulted &&
164 !shallowEqualObjects(this.options, prevOptions)
165 ) {
166 this.#client.getQueryCache().notify({
167 type: 'observerOptionsUpdated',
168 query: this.#currentQuery,
169 observer: this,
170 })
171 }
172​
173 const mounted = this.hasListeners()
174​
175 // Fetch if there are subscribers
176 if (
177 mounted &&
178 shouldFetchOptionally(
179 this.#currentQuery,
180 prevQuery,
181 this.options,
182 prevOptions,
183 )
184 ) {
185 this.#executeFetch()
186 }
187​
188 // Update result
189 this.updateResult()
190​
191 // Update stale interval if needed
192 if (
193 mounted &&
194 (this.#currentQuery !== prevQuery ||
195 resolveQueryValue(this.options.enabled, this.#currentQuery) !==
196 resolveQueryValue(prevOptions.enabled, this.#currentQuery) ||
197 resolveQueryValue(this.options.staleTime, this.#currentQuery) !==
198 resolveQueryValue(prevOptions.staleTime, this.#currentQuery))
199 ) {
200 this.#updateStaleTimeout()
201 }
202​
203 const nextRefetchInterval = this.#computeRefetchInterval()
204​
205 // Update refetch interval if needed
206 if (
207 mounted &&
208 (this.#currentQuery !== prevQuery ||
209 resolveQueryValue(this.options.enabled, this.#currentQuery) !==
210 resolveQueryValue(prevOptions.enabled, this.#currentQuery) ||
211 nextRefetchInterval !== this.#currentRefetchInterval)
212 ) {
213 this.#updateRefetchInterval(nextRefetchInterval)
214 }
215 }
216​
217 getOptimisticResult(
218 options: DefaultedQueryObserverOptions<
219 TQueryFnData,
220 TError,
221 TData,
222 TQueryData,
223 TQueryKey
224 >,
225 ): QueryObserverResult<TData, TError> {
226 const query = this.#client.getQueryCache().build(this.#client, options)
227​
228 const result = this.createResult(query, options)
229​
230 if (!shallowEqualObjects(this.getCurrentResult(), result)) {
231 // this assigns the optimistic result to the current Observer
232 // because if the query function changes, useQuery will be performing
233 // an effect where it would fetch again.
234 // When the fetch finishes, we perform a deep data cloning in order
235 // to reuse objects references. This deep data clone is performed against
236 // the `observer.currentResult.data` property
237 // When QueryKey changes, we refresh the query and get new `optimistic`
238 // result, while we leave the `observer.currentResult`, so when new data
239 // arrives, it finds the old `observer.currentResult` which is related
240 // to the old QueryKey. Which means that currentResult and selectData are
241 // out of sync already.
242 // To solve this, we move the cursor of the currentResult every time
243 // an observer reads an optimistic value.
244​
245 // When keeping the previous data, the result doesn't change until new
246 // data arrives.
247 this.#currentResult = result
248 this.#currentResultOptions = this.options
249 this.#currentResultState = this.#currentQuery.state
250 }
251 return result
252 }
253​
254 getCurrentResult(): QueryObserverResult<TData, TError> {
255 return this.#currentResult
256 }
257​
258 trackResult(
259 result: QueryObserverResult<TData, TError>,
260 onPropTracked?: (key: keyof QueryObserverResult) => void,
261 ): QueryObserverResult<TData, TError> {
262 return new Proxy(result, {
263 get: (target, key) => {
264 this.trackProp(key as keyof QueryObserverResult)
265 onPropTracked?.(key as keyof QueryObserverResult)
266 return Reflect.get(target, key)
267 },
268 })
269 }
270​
271 trackProp(key: keyof QueryObserverResult) {
272 this.#trackedProps.add(key)
273 }
274​
275 getCurrentQuery(): Query<TQueryFnData, TError, TQueryData, TQueryKey> {
276 return this.#currentQuery
277 }
278​
279 refetch({ ...options }: RefetchOptions = {}): Promise<
280 QueryObserverResult<TData, TError>
281 > {
282 return this.fetch({
283 ...options,
284 })
285 }
286​
287 fetchOptimistic(
288 options: QueryObserverOptions<
289 TQueryFnData,
290 TError,
291 TData,
292 TQueryData,
293 TQueryKey
294 >,
295 ): Promise<QueryObserverResult<TData, TError>> {
296 const defaultedOptions = this.#client.defaultQueryOptions(options)
297​
298 const query = this.#client
299 .getQueryCache()
300 .build(this.#client, defaultedOptions)
301​
302 let unsubscribe = () => {}
303 let resolveEarly:
304 | ((result: QueryObserverResult<TData, TError>) => void)
305 | undefined
306​
307 const cachePromise = new Promise<QueryObserverResult<TData, TError>>(
308 (resolve) => {
309 resolveEarly = resolve
310 unsubscribe = this.#client.getQueryCache().subscribe((event) => {
311 if (
312 event.type === 'updated' &&
313 event.query.queryHash === query.queryHash &&
314 query.state.data !== undefined
315 ) {
316 unsubscribe()
317 resolve(this.createResult(query, defaultedOptions))
318 }
319 })
320 },
321 )
322​
323 return Promise.race([
324 query
325 .fetch()
326 .then(() => {
327 const result = this.createResult(query, defaultedOptions)
328 // Settle the subscriber promise so both branches always settle.
329 // This value is ignored by Promise.race since the fetch branch already won.
330 resolveEarly?.(result)
331 return result
332 })
333 .finally(() => {
334 unsubscribe()
335 }),
336 cachePromise,
337 ])
338 }
339​
340 protected fetch(
341 fetchOptions: ObserverFetchOptions,
342 ): Promise<QueryObserverResult<TData, TError>> {
343 return this.#executeFetch({
344 ...fetchOptions,
345 cancelRefetch: fetchOptions.cancelRefetch ?? true,
346 }).then(() => {
347 this.updateResult()
348 return this.#currentResult
349 })
350 }
351​
352 #executeFetch(
353 fetchOptions?: Omit<ObserverFetchOptions, 'initialPromise'>,
354 ): Promise<TQueryData | undefined> {
355 // Make sure we reference the latest query as the current one might have been removed
356 this.#updateQuery()
357​
358 // Fetch
359 let promise: Promise<TQueryData | undefined> = this.#currentQuery.fetch(
360 this.options,
361 fetchOptions,
362 )
363​
364 if (!fetchOptions?.throwOnError) {
365 promise = promise.catch(noop)
366 }
367​
368 return promise
369 }
370​
371 #shouldScheduleTimer(timeout: unknown): timeout is number {
372 return (
373 !isServerEnvironment() &&
374 resolveQueryValue(this.options.enabled, this.#currentQuery) !== false &&
375 isValidTimeout(timeout)
376 )
377 }
378​
379 #updateStaleTimeout(): void {
380 this.#clearStaleTimeout()
381 const staleTime = resolveQueryValue(
382 this.options.staleTime,
383 this.#currentQuery,
384 )
385​
386 if (this.#currentResult.isStale || !this.#shouldScheduleTimer(staleTime)) {
387 return
388 }
389​
390 const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime)
391​
392 // The timeout is sometimes triggered 1 ms before the stale time expiration.
393 // To mitigate this issue we always add 1 ms to the timeout.
394 const timeout = time + 1
395​
396 this.#staleTimeoutId = timeoutManager.setTimeout(() => {
397 if (!this.#currentResult.isStale) {
398 this.updateResult()
399 }
400 }, timeout)
401 }
402​
403 #computeRefetchInterval() {
404 return (
405 (typeof this.options.refetchInterval === 'function'
406 ? this.options.refetchInterval(this.#currentQuery)
407 : this.options.refetchInterval) ?? false
408 )
409 }
410​
411 #updateRefetchInterval(nextInterval: number | false): void {
412 this.#clearRefetchInterval()
413​
414 this.#currentRefetchInterval = nextInterval
415​
416 if (
417 this.#currentRefetchInterval === 0 ||
418 !this.#shouldScheduleTimer(this.#currentRefetchInterval)
419 ) {
420 return
421 }
422​
423 this.#refetchIntervalId = timeoutManager.setInterval(() => {
424 if (
425 this.options.refetchIntervalInBackground ||
426 focusManager.isFocused()
427 ) {
428 this.#executeFetch()
429 }
430 }, this.#currentRefetchInterval)
431 }
432​
433 #updateTimers(): void {
434 this.#updateStaleTimeout()
435 this.#updateRefetchInterval(this.#computeRefetchInterval())
436 }
437​
438 #clearStaleTimeout(): void {
439 if (this.#staleTimeoutId !== undefined) {
440 timeoutManager.clearTimeout(this.#staleTimeoutId)
441 this.#staleTimeoutId = undefined
442 }
443 }
444​
445 #clearRefetchInterval(): void {
446 if (this.#refetchIntervalId !== undefined) {
447 timeoutManager.clearInterval(this.#refetchIntervalId)
448 this.#refetchIntervalId = undefined
449 }
450 }
451​
452 protected createResult(
453 query: Query<TQueryFnData, TError, TQueryData, TQueryKey>,
454 options: QueryObserverOptions<
455 TQueryFnData,
456 TError,
457 TData,
458 TQueryData,
459 TQueryKey
460 >,
461 ): QueryObserverResult<TData, TError> {
462 const prevQuery = this.#currentQuery
463 const prevOptions = this.options
464 const prevResult = this.#currentResult as
465 | QueryObserverResult<TData, TError>
466 | undefined
467 const prevResultState = this.#currentResultState
468 const prevResultOptions = this.#currentResultOptions
469 const queryChange = query !== prevQuery
470 const queryInitialState = queryChange
471 ? query.state
472 : this.#currentQueryInitialState
473​
474 const { state } = query
475 let newState = { ...state }
476 let isPlaceholderData = false
477 let data: TData | undefined
478​
479 // Optimistically set result in fetching state if needed
480 if (options._optimisticResults) {
481 const mounted = this.hasListeners()
482​
483 const fetchOnMount = !mounted && shouldFetchOnMount(query, options)
484​
485 const fetchOptionally =
486 mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions)
487​
488 if (fetchOnMount || fetchOptionally) {
489 newState = {
490 ...newState,
491 ...fetchState(state.data, query.options),
492 }
493 }
494 if (options._optimisticResults === 'isRestoring') {
495 newState.fetchStatus = 'idle'
496 }
497 }
498​
499 let { error, errorUpdatedAt, status } = newState
500​
501 // Per default, use query data
502 data = newState.data as unknown as TData
503 let skipSelect = false
504​
505 // use placeholderData if needed
506 if (
507 options.placeholderData !== undefined &&
508 data === undefined &&
509 status === 'pending'
510 ) {
511 let placeholderData
512​
513 // Memoize placeholder data
514 if (
515 prevResult?.isPlaceholderData &&
516 options.placeholderData === prevResultOptions?.placeholderData
517 ) {
518 placeholderData = prevResult.data
519 // we have to skip select when reading this memoization
520 // because prevResult.data is already "selected"
521 skipSelect = true
522 } else {
523 // compute placeholderData
524 placeholderData =
525 typeof options.placeholderData === 'function'
526 ? (
527 options.placeholderData as unknown as PlaceholderDataFunction<TQueryData>
528 )(
529 this.#lastQueryWithDefinedData?.state.data,
530 this.#lastQueryWithDefinedData as any,
531 )
532 : options.placeholderData
533 }
534​
535 if (placeholderData !== undefined) {
536 status = 'success'
537 data = replaceData(
538 prevResult?.data,
539 placeholderData as unknown,
540 options,
541 ) as TData
542 isPlaceholderData = true
543 }
544 }
545​
546 // Select data if needed
547 // this also runs placeholderData through the select function
548 if (options.select && data !== undefined && !skipSelect) {
549 // Memoize select result
550 if (
551 prevResult &&
552 data === prevResultState?.data &&
553 options.select === this.#selectFn
554 ) {
555 data = this.#selectResult
556 } else {
557 try {
558 this.#selectFn = options.select
559 data = options.select(data as any)
560 data = replaceData(prevResult?.data, data, options)
561 this.#selectResult = data
562 this.#selectError = null
563 } catch (selectError) {
564 this.#selectError = selectError as TError
565 }
566 }
567 } else if (data === undefined) {
568 // a stored select error belongs to previously selected data; once that
569 // data is gone (query switch or reset), it must not leak into this result
570 this.#selectError = null
571 }
572​
573 if (this.#selectError) {
574 error = this.#selectError
575 data = this.#selectResult
576 errorUpdatedAt = Date.now()
577 status = 'error'
578 isPlaceholderData = false
579 }
580​
581 const isFetching = newState.fetchStatus === 'fetching'
582 const isPending = status === 'pending'
583 const isError = status === 'error'
584​
585 const isLoading = isPending && isFetching
586 const hasData = data !== undefined
587​
588 const result: QueryObserverBaseResult<TData, TError> = {
589 status,
590 fetchStatus: newState.fetchStatus,
591 isPending,
592 isSuccess: status === 'success',
593 isError,
594 isInitialLoading: isLoading,
595 isLoading,
596 data,
597 dataUpdatedAt: newState.dataUpdatedAt,
598 error,
599 errorUpdatedAt,
600 failureCount: newState.fetchFailureCount,
601 failureReason: newState.fetchFailureReason,
602 errorUpdateCount: newState.errorUpdateCount,
603 isFetched: query.isFetched(),
604 isFetchedAfterMount:
605 newState.dataUpdateCount > queryInitialState.dataUpdateCount ||
606 newState.errorUpdateCount > queryInitialState.errorUpdateCount,
607 isFetching,
608 isRefetching: isFetching && !isPending,
609 isLoadingError: isError && !hasData,
610 isPaused: newState.fetchStatus === 'paused',
611 isPlaceholderData,
612 isRefetchError: isError && hasData,
613 isStale: isStale(query, options),
614 refetch: this.refetch,
615 isEnabled: resolveQueryValue(options.enabled, query) !== false,
616 }
617​
618 const nextResult = result as QueryObserverResult<TData, TError>
619​
620 return nextResult
621 }
622​
623 updateResult(): void {
624 const prevResult = this.#currentResult as
625 | QueryObserverResult<TData, TError>
626 | undefined
627​
628 const nextResult = this.createResult(this.#currentQuery, this.options)
629​
630 this.#currentResultState = this.#currentQuery.state
631 this.#currentResultOptions = this.options
632​
633 if (this.#currentResultState.data !== undefined) {
634 this.#lastQueryWithDefinedData = this.#currentQuery
635 }
636​
637 // Only notify and update result if something has changed
638 if (shallowEqualObjects(nextResult, prevResult)) {
639 return
640 }
641​
642 this.#currentResult = nextResult
643​
644 const shouldNotifyListeners = (): boolean => {
645 if (!prevResult) {
646 return true
647 }
648​
649 const { notifyOnChangeProps } = this.options
650 const notifyOnChangePropsValue =
651 typeof notifyOnChangeProps === 'function'
652 ? notifyOnChangeProps()
653 : notifyOnChangeProps
654​
655 if (
656 notifyOnChangePropsValue === 'all' ||
657 (!notifyOnChangePropsValue && !this.#trackedProps.size)
658 ) {
659 return true
660 }
661​
662 const includedProps = new Set(
663 notifyOnChangePropsValue ?? this.#trackedProps,
664 )
665​
666 if (this.options.throwOnError) {
667 includedProps.add('error')
668 }
669​
670 return Object.keys(this.#currentResult).some((key) => {
671 const typedKey = key as keyof QueryObserverResult
672 const changed = this.#currentResult[typedKey] !== prevResult[typedKey]
673​
674 return changed && includedProps.has(typedKey)
675 })
676 }
677​
678 const notifyListeners = shouldNotifyListeners()
679​
680 notifyManager.batch(() => {
681 // First, trigger the listeners
682 if (notifyListeners) {
683 this.listeners.forEach((listener) => {
684 listener(this.#currentResult)
685 })
686 }
687​
688 // Then the cache listeners
689 this.#client.getQueryCache().notify({
690 query: this.#currentQuery,
691 type: 'observerResultsUpdated',
692 })
693 })
694 }
695​
696 #updateQuery(): void {
697 const query = this.#client.getQueryCache().build(this.#client, this.options)
698​
699 if (query === this.#currentQuery) {
700 return
701 }
702​
703 const prevQuery = this.#currentQuery as
704 | Query<TQueryFnData, TError, TQueryData, TQueryKey>
705 | undefined
706 this.#currentQuery = query
707 this.#currentQueryInitialState = query.state
708​
709 if (this.hasListeners()) {
710 prevQuery?.removeObserver(this)
711 query.addObserver(this)
712 }
713 }
714​
715 onQueryUpdate(): void {
716 this.updateResult()
717​
718 if (this.hasListeners()) {
719 this.#updateTimers()
720 }
721 }
723​
724function shouldLoadOnMount(
725 query: Query<any, any, any, any>,
726 options: QueryObserverOptions<any, any, any, any>,
727): boolean {
728 return (
729 resolveQueryValue(options.enabled, query) !== false &&
730 query.state.data === undefined &&
731 !(
732 query.state.status === 'error' &&
733 resolveQueryValue(options.retryOnMount, query) === false
734 )
735 )
737​
738function shouldFetchOnMount(
739 query: Query<any, any, any, any>,
740 options: QueryObserverOptions<any, any, any, any, any>,
741): boolean {
742 return (
743 shouldLoadOnMount(query, options) ||
744 (query.state.data !== undefined &&
745 shouldFetchOn(query, options, options.refetchOnMount))
746 )
748​
749function shouldFetchOn(
750 query: Query<any, any, any, any>,
751 options: QueryObserverOptions<any, any, any, any, any>,
752 field: (typeof options)['refetchOnMount'] &
753 (typeof options)['refetchOnWindowFocus'] &
754 (typeof options)['refetchOnReconnect'],
755) {
756 if (
757 resolveQueryValue(options.enabled, query) !== false &&
758 resolveQueryValue(options.staleTime, query) !== 'static'
759 ) {
760 const value = typeof field === 'function' ? field(query) : field
761​
762 return value === 'always' || (value !== false && isStale(query, options))
763 }
764 return false
766​
767function shouldFetchOptionally(
768 query: Query<any, any, any, any>,
769 prevQuery: Query<any, any, any, any>,
770 options: QueryObserverOptions<any, any, any, any, any>,
771 prevOptions: QueryObserverOptions<any, any, any, any, any>,
772): boolean {
773 return (
774 (query !== prevQuery ||
775 resolveQueryValue(prevOptions.enabled, query) === false) &&
776 (!options.suspense || query.state.status !== 'error') &&
777 isStale(query, options)
778 )
780​
781function isStale(
782 query: Query<any, any, any, any>,
783 options: QueryObserverOptions<any, any, any, any, any>,
784): boolean {
785 return (
786 resolveQueryValue(options.enabled, query) !== false &&
787 query.isStaleByTime(resolveQueryValue(options.staleTime, query))
788 )