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

queryObserver.ts

898 lines26.1 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​
37/**
38 * A `QueryObserver` watches a single query in the `QueryCache` and computes a
39 * `QueryObserverResult` from its state, recomputing and notifying subscribers
40 * whenever the underlying query (or the observer's options) changes. It is
41 * the primitive that framework adapters (e.g. `useQuery`) build their hooks
42 * on top of, but it can also be used directly to observe and switch between
43 * queries outside of any framework.
44 *
45 * @example
46 * ```ts
47 * const observer = new QueryObserver(queryClient, {
48 * queryKey: ['posts'],
49 * queryFn: fetchPosts,
50 * })
51 *
52 * const unsubscribe = observer.subscribe((result) => {
53 * console.log(result.data)
54 * })
55 * ```
56 */
57export class QueryObserver<
58 TQueryFnData = unknown,
59 TError = DefaultError,
60 TData = TQueryFnData,
61 TQueryData = TQueryFnData,
62 TQueryKey extends QueryKey = QueryKey,
63> extends Subscribable<QueryObserverListener<TData, TError>> {
64 #client: QueryClient
65 #currentQuery: Query<TQueryFnData, TError, TQueryData, TQueryKey> = undefined!
66 #currentQueryInitialState: QueryState<TQueryData, TError> = undefined!
67 #currentResult: QueryObserverResult<TData, TError> = undefined!
68 #currentResultState?: QueryState<TQueryData, TError>
69 #currentResultOptions?: QueryObserverOptions<
70 TQueryFnData,
71 TError,
72 TData,
73 TQueryData,
74 TQueryKey
75 >
76 #selectError: TError | null
77 #selectFn?: (data: TQueryData) => TData
78 #selectResult?: TData
79 // This property keeps track of the last query with defined data.
80 // It will be used to pass the previous data and query to the placeholder function between renders.
81 #lastQueryWithDefinedData?: Query<TQueryFnData, TError, TQueryData, TQueryKey>
82 #staleTimeoutId?: ManagedTimerId
83 #refetchIntervalId?: ManagedTimerId
84 #currentRefetchInterval?: number | false
85 #trackedProps = new Set<keyof QueryObserverResult>()
86​
87 constructor(
88 client: QueryClient,
89 public options: QueryObserverOptions<
90 TQueryFnData,
91 TError,
92 TData,
93 TQueryData,
94 TQueryKey
95 >,
96 ) {
97 super()
98​
99 this.#client = client
100 this.#selectError = null
101​
102 this.bindMethods()
103 this.setOptions(options)
104 }
105​
106 protected bindMethods(): void {
107 this.refetch = this.refetch.bind(this)
108 }
109​
110 protected onSubscribe(): void {
111 if (this.listeners.size === 1) {
112 this.#currentQuery.addObserver(this)
113​
114 if (shouldFetchOnMount(this.#currentQuery, this.options)) {
115 this.#executeFetch()
116 } else {
117 this.updateResult()
118 }
119​
120 this.#updateTimers()
121 }
122 }
123​
124 protected onUnsubscribe(): void {
125 if (!this.hasListeners()) {
126 this.destroy()
127 }
128 }
129​
130 /**
131 * Returns whether the observed query is currently stale and configured
132 * (via the `refetchOnReconnect` option) to refetch when the network
133 * reconnects.
134 */
135 shouldFetchOnReconnect(): boolean {
136 return shouldFetchOn(
137 this.#currentQuery,
138 this.options,
139 this.options.refetchOnReconnect,
140 )
141 }
142​
143 /**
144 * Returns whether the observed query is currently stale and configured
145 * (via the `refetchOnWindowFocus` option) to refetch when the window
146 * regains focus.
147 */
148 shouldFetchOnWindowFocus(): boolean {
149 return shouldFetchOn(
150 this.#currentQuery,
151 this.options,
152 this.options.refetchOnWindowFocus,
153 )
154 }
155​
156 /**
157 * Stops observing the current query: clears all listeners, cancels the
158 * stale and refetch-interval timers, and removes this observer from the
159 * query it was observing.
160 */
161 destroy(): void {
162 this.listeners = new Set()
163 this.#clearStaleTimeout()
164 this.#clearRefetchInterval()
165 this.#currentQuery.removeObserver(this)
166 }
167​
168 /**
169 * Updates the observer's options. This will re-resolve the query being
170 * observed (switching to a different query if the `queryKey` changed),
171 * trigger a fetch if the new options require one and the observer has
172 * subscribers, recompute the current result, and reschedule the stale and
173 * refetch-interval timers as needed.
174 *
175 * @example
176 * ```ts
177 * observer.setOptions({ queryKey: ['posts', 1], queryFn: () => fetchPost(1) })
178 * // later: switch to a different query, reusing the same observer
179 * observer.setOptions({ queryKey: ['posts', 2], queryFn: () => fetchPost(2) })
180 * ```
181 */
182 setOptions(
183 options: QueryObserverOptions<
184 TQueryFnData,
185 TError,
186 TData,
187 TQueryData,
188 TQueryKey
189 >,
190 ): void {
191 const prevOptions = this.options
192 const prevQuery = this.#currentQuery
193​
194 this.options = this.#client.defaultQueryOptions(options)
195​
196 if (
197 this.options.enabled !== undefined &&
198 typeof this.options.enabled !== 'boolean' &&
199 typeof this.options.enabled !== 'function' &&
200 typeof resolveQueryValue(this.options.enabled, this.#currentQuery) !==
201 'boolean'
202 ) {
203 throw new Error(
204 'Expected enabled to be a boolean or a callback that returns a boolean',
205 )
206 }
207​
208 this.#updateQuery()
209 this.#currentQuery.setOptions(this.options)
210​
211 if (
212 prevOptions._defaulted &&
213 !shallowEqualObjects(this.options, prevOptions)
214 ) {
215 this.#client.getQueryCache().notify({
216 type: 'observerOptionsUpdated',
217 query: this.#currentQuery,
218 observer: this,
219 })
220 }
221​
222 const mounted = this.hasListeners()
223​
224 // Fetch if there are subscribers
225 if (
226 mounted &&
227 shouldFetchOptionally(
228 this.#currentQuery,
229 prevQuery,
230 this.options,
231 prevOptions,
232 )
233 ) {
234 this.#executeFetch()
235 }
236​
237 // Update result
238 this.updateResult()
239​
240 // Update stale interval if needed
241 if (
242 mounted &&
243 (this.#currentQuery !== prevQuery ||
244 resolveQueryValue(this.options.enabled, this.#currentQuery) !==
245 resolveQueryValue(prevOptions.enabled, this.#currentQuery) ||
246 resolveQueryValue(this.options.staleTime, this.#currentQuery) !==
247 resolveQueryValue(prevOptions.staleTime, this.#currentQuery))
248 ) {
249 this.#updateStaleTimeout()
250 }
251​
252 const nextRefetchInterval = this.#computeRefetchInterval()
253​
254 // Update refetch interval if needed
255 if (
256 mounted &&
257 (this.#currentQuery !== prevQuery ||
258 resolveQueryValue(this.options.enabled, this.#currentQuery) !==
259 resolveQueryValue(prevOptions.enabled, this.#currentQuery) ||
260 nextRefetchInterval !== this.#currentRefetchInterval)
261 ) {
262 this.#updateRefetchInterval(nextRefetchInterval)
263 }
264 }
265​
266 /**
267 * Computes the result the observer would produce for the given (already-defaulted) options
268 * right now, building the underlying `Query` if it doesn't exist yet, without waiting for a
269 * subscription callback. Called by framework adapters on every render (e.g. `useQuery`) so the
270 * returned value is available synchronously, ahead of `setOptions` triggering an actual fetch.
271 */
272 getOptimisticResult(
273 options: DefaultedQueryObserverOptions<
274 TQueryFnData,
275 TError,
276 TData,
277 TQueryData,
278 TQueryKey
279 >,
280 ): QueryObserverResult<TData, TError> {
281 const query = this.#client.getQueryCache().build(this.#client, options)
282​
283 const result = this.createResult(query, options)
284​
285 if (!shallowEqualObjects(this.getCurrentResult(), result)) {
286 // this assigns the optimistic result to the current Observer
287 // because if the query function changes, useQuery will be performing
288 // an effect where it would fetch again.
289 // When the fetch finishes, we perform a deep data cloning in order
290 // to reuse objects references. This deep data clone is performed against
291 // the `observer.currentResult.data` property
292 // When QueryKey changes, we refresh the query and get new `optimistic`
293 // result, while we leave the `observer.currentResult`, so when new data
294 // arrives, it finds the old `observer.currentResult` which is related
295 // to the old QueryKey. Which means that currentResult and selectData are
296 // out of sync already.
297 // To solve this, we move the cursor of the currentResult every time
298 // an observer reads an optimistic value.
299​
300 // When keeping the previous data, the result doesn't change until new
301 // data arrives.
302 this.#currentResult = result
303 this.#currentResultOptions = this.options
304 this.#currentResultState = this.#currentQuery.state
305 }
306 return result
307 }
308​
309 /**
310 * Returns the most recently computed `QueryObserverResult` for the
311 * observed query. This is a point-in-time read; to be notified of updates
312 * as they happen, subscribe to the observer instead (its inherited
313 * `subscribe` method).
314 *
315 * @example
316 * ```ts
317 * const result = observer.getCurrentResult()
318 * console.log(result.status, result.data)
319 * ```
320 */
321 getCurrentResult(): QueryObserverResult<TData, TError> {
322 return this.#currentResult
323 }
324​
325 /**
326 * Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via
327 * {@link QueryObserver#trackProp} (and an optional `onPropTracked` callback). Used by framework
328 * adapters when `notifyOnChangeProps` is not set, to implement its default "only re-render on
329 * properties you actually read" behavior.
330 */
331 trackResult(
332 result: QueryObserverResult<TData, TError>,
333 onPropTracked?: (key: keyof QueryObserverResult) => void,
334 ): QueryObserverResult<TData, TError> {
335 return new Proxy(result, {
336 get: (target, key) => {
337 this.trackProp(key as keyof QueryObserverResult)
338 onPropTracked?.(key as keyof QueryObserverResult)
339 return Reflect.get(target, key)
340 },
341 })
342 }
343​
344 /**
345 * Records that the given `QueryObserverResult` property was read, so a subsequent update only
346 * notifies this observer if a tracked property actually changed. Normally called indirectly via
347 * {@link QueryObserver#trackResult}'s proxy; exposed directly for adapters that track property
348 * access themselves (e.g. through their own reactivity system) instead of via the proxy.
349 */
350 trackProp(key: keyof QueryObserverResult) {
351 this.#trackedProps.add(key)
352 }
353​
354 /**
355 * Returns the `Query` instance this observer is currently observing.
356 */
357 getCurrentQuery(): Query<TQueryFnData, TError, TQueryData, TQueryKey> {
358 return this.#currentQuery
359 }
360​
361 /**
362 * Refetches the observed query and returns a promise that resolves with
363 * the resulting `QueryObserverResult`.
364 *
365 * @example
366 * ```ts
367 * const result = await observer.refetch({ cancelRefetch: false })
368 * console.log(result.data)
369 * ```
370 */
371 refetch({ ...options }: RefetchOptions = {}): Promise<
372 QueryObserverResult<TData, TError>
373 > {
374 return this.fetch({
375 ...options,
376 })
377 }
378​
379 /**
380 * Fetches a query defined by the given options without affecting this
381 * observer's own tracked query or result, and returns a promise that
382 * resolves with the `QueryObserverResult` for that fetch. This is useful
383 * for prefetching data that another observer (e.g. a query about to be
384 * navigated to) will need, ahead of time.
385 *
386 * @example
387 * ```ts
388 * const result = await observer.fetchOptimistic({
389 * queryKey: ['posts', 2],
390 * queryFn: () => fetchPost(2),
391 * })
392 * console.log(result.data)
393 * ```
394 */
395 fetchOptimistic(
396 options: QueryObserverOptions<
397 TQueryFnData,
398 TError,
399 TData,
400 TQueryData,
401 TQueryKey
402 >,
403 ): Promise<QueryObserverResult<TData, TError>> {
404 const defaultedOptions = this.#client.defaultQueryOptions(options)
405​
406 const query = this.#client
407 .getQueryCache()
408 .build(this.#client, defaultedOptions)
409​
410 let unsubscribe = () => {}
411 let resolveEarly:
412 ((result: QueryObserverResult<TData, TError>) => void) | undefined
413​
414 const cachePromise = new Promise<QueryObserverResult<TData, TError>>(
415 (resolve) => {
416 resolveEarly = resolve
417 unsubscribe = this.#client.getQueryCache().subscribe((event) => {
418 if (
419 event.type === 'updated' &&
420 event.query.queryHash === query.queryHash &&
421 query.state.data !== undefined
422 ) {
423 unsubscribe()
424 resolve(this.createResult(query, defaultedOptions))
425 }
426 })
427 },
428 )
429​
430 return Promise.race([
431 query
432 .fetch()
433 .then(() => {
434 const result = this.createResult(query, defaultedOptions)
435 // Settle the subscriber promise so both branches always settle.
436 // This value is ignored by Promise.race since the fetch branch already won.
437 resolveEarly?.(result)
438 return result
439 })
440 .finally(() => {
441 unsubscribe()
442 }),
443 cachePromise,
444 ])
445 }
446​
447 protected fetch(
448 fetchOptions: ObserverFetchOptions,
449 ): Promise<QueryObserverResult<TData, TError>> {
450 return this.#executeFetch({
451 ...fetchOptions,
452 cancelRefetch: fetchOptions.cancelRefetch ?? true,
453 }).then(() => {
454 this.updateResult()
455 return this.#currentResult
456 })
457 }
458​
459 #executeFetch(
460 fetchOptions?: Omit<ObserverFetchOptions, 'initialPromise'>,
461 ): Promise<TQueryData | undefined> {
462 // Make sure we reference the latest query as the current one might have been removed
463 this.#updateQuery()
464​
465 // Fetch
466 let promise: Promise<TQueryData | undefined> = this.#currentQuery.fetch(
467 this.options,
468 fetchOptions,
469 )
470​
471 if (!fetchOptions?.throwOnError) {
472 promise = promise.catch(noop)
473 }
474​
475 return promise
476 }
477​
478 #shouldScheduleTimer(timeout: unknown): timeout is number {
479 return (
480 !isServerEnvironment() &&
481 resolveQueryValue(this.options.enabled, this.#currentQuery) !== false &&
482 isValidTimeout(timeout)
483 )
484 }
485​
486 #updateStaleTimeout(): void {
487 this.#clearStaleTimeout()
488 const staleTime = resolveQueryValue(
489 this.options.staleTime,
490 this.#currentQuery,
491 )
492​
493 if (this.#currentResult.isStale || !this.#shouldScheduleTimer(staleTime)) {
494 return
495 }
496​
497 const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime)
498​
499 // The timeout is sometimes triggered 1 ms before the stale time expiration.
500 // To mitigate this issue we always add 1 ms to the timeout.
501 const timeout = time + 1
502​
503 this.#staleTimeoutId = timeoutManager.setTimeout(() => {
504 if (!this.#currentResult.isStale) {
505 this.updateResult()
506 }
507 }, timeout)
508 }
509​
510 #computeRefetchInterval() {
511 return (
512 resolveQueryValue(this.options.refetchInterval, this.#currentQuery) ??
513 false
514 )
515 }
516​
517 #updateRefetchInterval(nextInterval: number | false): void {
518 this.#clearRefetchInterval()
519​
520 this.#currentRefetchInterval = nextInterval
521​
522 if (
523 this.#currentRefetchInterval === 0 ||
524 !this.#shouldScheduleTimer(this.#currentRefetchInterval)
525 ) {
526 return
527 }
528​
529 this.#refetchIntervalId = timeoutManager.setInterval(() => {
530 if (
531 this.options.refetchIntervalInBackground ||
532 focusManager.isFocused()
533 ) {
534 this.#executeFetch()
535 }
536 }, this.#currentRefetchInterval)
537 }
538​
539 #updateTimers(): void {
540 this.#updateStaleTimeout()
541 this.#updateRefetchInterval(this.#computeRefetchInterval())
542 }
543​
544 #clearStaleTimeout(): void {
545 if (this.#staleTimeoutId !== undefined) {
546 timeoutManager.clearTimeout(this.#staleTimeoutId)
547 this.#staleTimeoutId = undefined
548 }
549 }
550​
551 #clearRefetchInterval(): void {
552 if (this.#refetchIntervalId !== undefined) {
553 timeoutManager.clearInterval(this.#refetchIntervalId)
554 this.#refetchIntervalId = undefined
555 }
556 }
557​
558 protected createResult(
559 query: Query<TQueryFnData, TError, TQueryData, TQueryKey>,
560 options: QueryObserverOptions<
561 TQueryFnData,
562 TError,
563 TData,
564 TQueryData,
565 TQueryKey
566 >,
567 ): QueryObserverResult<TData, TError> {
568 const prevQuery = this.#currentQuery
569 const prevOptions = this.options
570 const prevResult = this.#currentResult as
571 QueryObserverResult<TData, TError> | undefined
572 const prevResultState = this.#currentResultState
573 const prevResultOptions = this.#currentResultOptions
574 const queryChange = query !== prevQuery
575 const queryInitialState = queryChange
576 ? query.state
577 : this.#currentQueryInitialState
578​
579 const { state } = query
580 let newState = { ...state }
581 let isPlaceholderData = false
582 let data: TData | undefined
583​
584 // Optimistically set result in fetching state if needed
585 if (options._optimisticResults) {
586 const mounted = this.hasListeners()
587​
588 const fetchOnMount = !mounted && shouldFetchOnMount(query, options)
589​
590 const fetchOptionally =
591 mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions)
592​
593 if (fetchOnMount || fetchOptionally) {
594 newState = {
595 ...newState,
596 ...fetchState(state.data, query.options),
597 }
598 }
599 if (options._optimisticResults === 'isRestoring') {
600 newState.fetchStatus = 'idle'
601 }
602 }
603​
604 let { error, errorUpdatedAt, status } = newState
605​
606 // Per default, use query data
607 data = newState.data as unknown as TData
608 let skipSelect = false
609​
610 // use placeholderData if needed
611 if (
612 options.placeholderData !== undefined &&
613 data === undefined &&
614 status === 'pending'
615 ) {
616 let placeholderData
617​
618 // Memoize placeholder data
619 if (
620 prevResult?.isPlaceholderData &&
621 options.placeholderData === prevResultOptions?.placeholderData
622 ) {
623 placeholderData = prevResult.data
624 // we have to skip select when reading this memoization
625 // because prevResult.data is already "selected"
626 skipSelect = true
627 } else {
628 // compute placeholderData
629 placeholderData =
630 typeof options.placeholderData === 'function'
631 ? (
632 options.placeholderData as unknown as PlaceholderDataFunction<TQueryData>
633 )(
634 this.#lastQueryWithDefinedData?.state.data,
635 this.#lastQueryWithDefinedData as any,
636 )
637 : options.placeholderData
638 }
639​
640 if (placeholderData !== undefined) {
641 status = 'success'
642 data = replaceData(
643 prevResult?.data,
644 placeholderData as unknown,
645 options,
646 ) as TData
647 isPlaceholderData = true
648 }
649 }
650​
651 // Select data if needed
652 // this also runs placeholderData through the select function
653 if (options.select && data !== undefined && !skipSelect) {
654 // Memoize select result
655 if (
656 prevResult &&
657 data === prevResultState?.data &&
658 options.select === this.#selectFn
659 ) {
660 data = this.#selectResult
661 } else {
662 try {
663 this.#selectFn = options.select
664 data = options.select(data as any)
665 data = replaceData(prevResult?.data, data, options)
666 this.#selectResult = data
667 this.#selectError = null
668 } catch (selectError) {
669 this.#selectError = selectError as TError
670 }
671 }
672 } else if (data === undefined) {
673 // a stored select error belongs to previously selected data; once that
674 // data is gone (query switch or reset), it must not leak into this result
675 this.#selectError = null
676 }
677​
678 if (this.#selectError) {
679 error = this.#selectError
680 data = this.#selectResult
681 errorUpdatedAt = Date.now()
682 status = 'error'
683 isPlaceholderData = false
684 }
685​
686 const isFetching = newState.fetchStatus === 'fetching'
687 const isPending = status === 'pending'
688 const isError = status === 'error'
689​
690 const isLoading = isPending && isFetching
691 const hasData = data !== undefined
692​
693 const result: QueryObserverBaseResult<TData, TError> = {
694 status,
695 fetchStatus: newState.fetchStatus,
696 isPending,
697 isSuccess: status === 'success',
698 isError,
699 isInitialLoading: isLoading,
700 isLoading,
701 data,
702 dataUpdatedAt: newState.dataUpdatedAt,
703 error,
704 errorUpdatedAt,
705 failureCount: newState.fetchFailureCount,
706 failureReason: newState.fetchFailureReason,
707 errorUpdateCount: newState.errorUpdateCount,
708 isFetched: query.isFetched(),
709 isFetchedAfterMount:
710 newState.dataUpdateCount > queryInitialState.dataUpdateCount ||
711 newState.errorUpdateCount > queryInitialState.errorUpdateCount,
712 isFetching,
713 isRefetching: isFetching && !isPending,
714 isLoadingError: isError && !hasData,
715 isPaused: newState.fetchStatus === 'paused',
716 isPlaceholderData,
717 isRefetchError: isError && hasData,
718 isStale: isStale(query, options),
719 refetch: this.refetch,
720 isEnabled: resolveQueryValue(options.enabled, query) !== false,
721 }
722​
723 const nextResult = result as QueryObserverResult<TData, TError>
724​
725 return nextResult
726 }
727​
728 /**
729 * Recomputes and stores the current result from the current query/options, notifying listeners
730 * if it changed. Framework adapters call this right after subscribing to make sure no query
731 * update was missed in the gap between creating the observer and subscribing to it.
732 */
733 updateResult(): void {
734 const prevResult = this.#currentResult as
735 QueryObserverResult<TData, TError> | undefined
736​
737 const nextResult = this.createResult(this.#currentQuery, this.options)
738​
739 this.#currentResultState = this.#currentQuery.state
740 this.#currentResultOptions = this.options
741​
742 if (this.#currentResultState.data !== undefined) {
743 this.#lastQueryWithDefinedData = this.#currentQuery
744 }
745​
746 // Only notify and update result if something has changed
747 if (shallowEqualObjects(nextResult, prevResult)) {
748 return
749 }
750​
751 this.#currentResult = nextResult
752​
753 const shouldNotifyListeners = (): boolean => {
754 if (!prevResult) {
755 return true
756 }
757​
758 const { notifyOnChangeProps } = this.options
759 const notifyOnChangePropsValue =
760 typeof notifyOnChangeProps === 'function'
761 ? notifyOnChangeProps()
762 : notifyOnChangeProps
763​
764 if (
765 notifyOnChangePropsValue === 'all' ||
766 (!notifyOnChangePropsValue && !this.#trackedProps.size)
767 ) {
768 return true
769 }
770​
771 const includedProps = new Set(
772 notifyOnChangePropsValue ?? this.#trackedProps,
773 )
774​
775 if (this.options.throwOnError) {
776 includedProps.add('error')
777 }
778​
779 return Object.keys(this.#currentResult).some((key) => {
780 const typedKey = key as keyof QueryObserverResult
781 const changed = this.#currentResult[typedKey] !== prevResult[typedKey]
782​
783 return changed && includedProps.has(typedKey)
784 })
785 }
786​
787 const notifyListeners = shouldNotifyListeners()
788​
789 notifyManager.batch(() => {
790 // First, trigger the listeners
791 if (notifyListeners) {
792 this.listeners.forEach((listener) => {
793 listener(this.#currentResult)
794 })
795 }
796​
797 // Then the cache listeners
798 this.#client.getQueryCache().notify({
799 query: this.#currentQuery,
800 type: 'observerResultsUpdated',
801 })
802 })
803 }
804​
805 #updateQuery(): void {
806 const query = this.#client.getQueryCache().build(this.#client, this.options)
807​
808 if (query === this.#currentQuery) {
809 return
810 }
811​
812 const prevQuery = this.#currentQuery as
813 Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined
814 this.#currentQuery = query
815 this.#currentQueryInitialState = query.state
816​
817 if (this.hasListeners()) {
818 prevQuery?.removeObserver(this)
819 query.addObserver(this)
820 }
821 }
822​
823 /** @internal */
824 onQueryUpdate(): void {
825 this.updateResult()
826​
827 if (this.hasListeners()) {
828 this.#updateTimers()
829 }
830 }
832​
833function shouldLoadOnMount(
834 query: Query<any, any, any, any>,
835 options: QueryObserverOptions<any, any, any, any>,
836): boolean {
837 return (
838 resolveQueryValue(options.enabled, query) !== false &&
839 query.state.data === undefined &&
840 !(
841 query.state.status === 'error' &&
842 resolveQueryValue(options.retryOnMount, query) === false
843 )
844 )
846​
847function shouldFetchOnMount(
848 query: Query<any, any, any, any>,
849 options: QueryObserverOptions<any, any, any, any, any>,
850): boolean {
851 return (
852 shouldLoadOnMount(query, options) ||
853 (query.state.data !== undefined &&
854 shouldFetchOn(query, options, options.refetchOnMount))
855 )
857​
858function shouldFetchOn(
859 query: Query<any, any, any, any>,
860 options: QueryObserverOptions<any, any, any, any, any>,
861 field: (typeof options)['refetchOnMount'] &
862 (typeof options)['refetchOnWindowFocus'] &
863 (typeof options)['refetchOnReconnect'],
864) {
865 if (
866 resolveQueryValue(options.enabled, query) !== false &&
867 resolveQueryValue(options.staleTime, query) !== 'static'
868 ) {
869 const value = resolveQueryValue(field, query)
870​
871 return value === 'always' || (value !== false && isStale(query, options))
872 }
873 return false
875​
876function shouldFetchOptionally(
877 query: Query<any, any, any, any>,
878 prevQuery: Query<any, any, any, any>,
879 options: QueryObserverOptions<any, any, any, any, any>,
880 prevOptions: QueryObserverOptions<any, any, any, any, any>,
881): boolean {
882 return (
883 (query !== prevQuery ||
884 resolveQueryValue(prevOptions.enabled, query) === false) &&
885 (!options.suspense || query.state.status !== 'error') &&
886 isStale(query, options)
887 )
889​
890function isStale(
891 query: Query<any, any, any, any>,
892 options: QueryObserverOptions<any, any, any, any, any>,
893): boolean {
894 return (
895 resolveQueryValue(options.enabled, query) !== false &&
896 query.isStaleByTime(resolveQueryValue(options.staleTime, query))
897 )