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

queryObserver.ts

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