Open History to see the last commit
1import { isServer as isServerEnvironment } from './environmentManager'
2import { focusManager } from './focusManager'
3import { notifyManager } from './notifyManager'
4import { fetchState } from './query'
5import { Subscribable } from './subscribable'
6import { timeoutManager } from './timeoutManager'
7import {
8 isValidTimeout,
9 noop,
10 replaceData,
11 resolveQueryValue,
12 shallowEqualObjects,
13 timeUntilStale,
14} from './utils'
15import type { FetchOptions, Query, QueryState } from './query'
16import type { QueryClient } from './queryClient'
17import type { ManagedTimerId } from './timeoutManager'
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
35}
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 #currentResultOptions?: QueryObserverOptions<
68 TQueryFnData,
69 TError,
70 TData,
71 TQueryData,
72 TQueryKey
73 >
74 #selectError: TError | null
75 #selectFn?: (data: TQueryData) => TData
76 #selectInput?: unknown
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 = options
313 }
314 return result
315 }
316β
317 /**
318 * Returns the most recently computed `QueryObserverResult` for the
319 * observed query. This is a point-in-time read; to be notified of updates
320 * as they happen, subscribe to the observer instead (its inherited
321 * `subscribe` method).
322 * @returns The observer's latest result.
323 * @example
324 * ```ts
325 * const result = observer.getCurrentResult()
326 * console.log(result.status, result.data)
327 * ```
328 */
329 getCurrentResult(): QueryObserverResult<TData, TError> {
330 return this.#currentResult
331 }
332β
333 /**
334 * Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via
335 * {@link QueryObserver#trackProp} (and an optional `onPropTracked` callback). Used by framework
336 * adapters when `notifyOnChangeProps` is not set, to implement its default "only re-render on
337 * properties you actually read" behavior.
338 * @param result - The result to wrap.
339 * @param onPropTracked - Called with the name of each property that is read.
340 * @returns A proxy of `result` that tracks property reads.
341 */
342 trackResult(
343 result: QueryObserverResult<TData, TError>,
344 onPropTracked?: (key: keyof QueryObserverResult) => void,
345 ): QueryObserverResult<TData, TError> {
346 return new Proxy(result, {
347 get: (target, key) => {
348 this.trackProp(key as keyof QueryObserverResult)
349 onPropTracked?.(key as keyof QueryObserverResult)
350 return Reflect.get(target, key)
351 },
352 })
353 }
354β
355 /**
356 * Records that the given `QueryObserverResult` property was read, so a subsequent update only
357 * notifies this observer if a tracked property actually changed. Normally called indirectly via
358 * {@link QueryObserver#trackResult}'s proxy; exposed directly for adapters that track property
359 * access themselves (e.g. through their own reactivity system) instead of via the proxy.
360 * @param key - The name of the property that was read.
361 */
362 trackProp(key: keyof QueryObserverResult) {
363 this.#trackedProps.add(key)
364 }
365β
366 /**
367 * Returns the `Query` instance this observer is currently observing.
368 * @returns The observed query.
369 */
370 getCurrentQuery(): Query<TQueryFnData, TError, TQueryData, TQueryKey> {
371 return this.#currentQuery
372 }
373β
374 /**
375 * Refetches the observed query and returns a promise that resolves with
376 * the resulting `QueryObserverResult`.
377 * @param options - Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling
378 * it, and `throwOnError` to `true` to reject when the refetch fails.
379 * @returns A promise that resolves with the result after the refetch.
380 * @example
381 * ```ts
382 * const result = await observer.refetch({ cancelRefetch: false })
383 * console.log(result.data)
384 * ```
385 */
386 refetch({ ...options }: RefetchOptions = {}): Promise<
387 QueryObserverResult<TData, TError>
388 > {
389 return this.fetch({
390 ...options,
391 })
392 }
393β
394 /**
395 * Fetches a query defined by the given options without affecting this
396 * observer's own tracked query or result, and returns a promise that
397 * resolves with the `QueryObserverResult` for that fetch. This is useful
398 * for prefetching data that another observer (e.g. a query about to be
399 * navigated to) will need, ahead of time.
400 * @param options - The observer options of the query to fetch.
401 * @returns A promise that resolves with the result for the fetched query.
402 * @example
403 * ```ts
404 * const result = await observer.fetchOptimistic({
405 * queryKey: ['posts', 2],
406 * queryFn: () => fetchPost(2),
407 * })
408 * console.log(result.data)
409 * ```
410 */
411 fetchOptimistic(
412 options: QueryObserverOptions<
413 TQueryFnData,
414 TError,
415 TData,
416 TQueryData,
417 TQueryKey
418 >,
419 ): Promise<QueryObserverResult<TData, TError>> {
420 const defaultedOptions = this.#client.defaultQueryOptions(options)
421β
422 const query = this.#client
423 .getQueryCache()
424 .build(this.#client, defaultedOptions)
425β
426 let unsubscribe = () => {}
427 let resolveEarly:
428 | ((result: QueryObserverResult<TData, TError>) => void)
429 | undefined
430β
431 const cachePromise = new Promise<QueryObserverResult<TData, TError>>(
432 (resolve) => {
433 resolveEarly = resolve
434 unsubscribe = this.#client.getQueryCache().subscribe((event) => {
435 if (
436 event.type === 'updated' &&
437 event.query.queryHash === query.queryHash &&
438 query.state.data !== undefined
439 ) {
440 unsubscribe()
441 resolve(this.createResult(query, defaultedOptions))
442 }
443 })
444 },
445 )
446β
447 return Promise.race([
448 query
449 .fetch(defaultedOptions)
450 .then(() => {
451 const result = this.createResult(query, defaultedOptions)
452 // Settle the subscriber promise so both branches always settle.
453 // This value is ignored by Promise.race since the fetch branch already won.
454 resolveEarly?.(result)
455 return result
456 })
457 .finally(() => {
458 unsubscribe()
459 }),
460 cachePromise,
461 ])
462 }
463β
464 /**
465 * Fetches the observed query and updates the result once the fetch settles. Used by `refetch` and,
466 * in `InfiniteQueryObserver`, to fetch more pages.
467 * @param fetchOptions - Options for this fetch. `cancelRefetch` defaults to `true`.
468 * @returns A promise that resolves with the updated result.
469 */
470 protected fetch(
471 fetchOptions: ObserverFetchOptions,
472 ): Promise<QueryObserverResult<TData, TError>> {
473 return this.#executeFetch({
474 ...fetchOptions,
475 cancelRefetch: fetchOptions.cancelRefetch ?? true,
476 }).then(() => {
477 this.updateResult()
478 return this.#currentResult
479 })
480 }
481β
482 #executeFetch(
483 fetchOptions?: Omit<ObserverFetchOptions, 'initialPromise'>,
484 ): Promise<TQueryData | undefined> {
485 // Make sure we reference the latest query as the current one might have been removed
486 this.#updateQuery()
487β
488 // Fetch
489 let promise: Promise<TQueryData | undefined> = this.#currentQuery.fetch(
490 this.options,
491 fetchOptions,
492 )
493β
494 if (!fetchOptions?.throwOnError) {
495 promise = promise.catch(noop)
496 }
497β
498 return promise
499 }
500β
501 #shouldScheduleTimer(timeout: unknown): timeout is number {
502 return (
503 !isServerEnvironment() &&
504 resolveQueryValue(this.options.enabled, this.#currentQuery) !== false &&
505 isValidTimeout(timeout)
506 )
507 }
508β
509 #updateStaleTimeout(): void {
510 this.#clearStaleTimeout()
511 const staleTime = resolveQueryValue(
512 this.options.staleTime,
513 this.#currentQuery,
514 )
515β
516 if (this.#currentResult.isStale || !this.#shouldScheduleTimer(staleTime)) {
517 return
518 }
519β
520 const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime)
521β
522 // The timeout is sometimes triggered 1 ms before the stale time expiration.
523 // To mitigate this issue we always add 1 ms to the timeout.
524 const timeout = time + 1
525β
526 this.#staleTimeoutId = timeoutManager.setTimeout(() => {
527 if (!this.#currentResult.isStale) {
528 this.updateResult()
529 }
530 }, timeout)
531 }
532β
533 #computeRefetchInterval() {
534 return (
535 resolveQueryValue(this.options.refetchInterval, this.#currentQuery) ??
536 false
537 )
538 }
539β
540 #updateRefetchInterval(nextInterval: number | false): void {
541 this.#clearRefetchInterval()
542β
543 this.#currentRefetchInterval = nextInterval
544β
545 if (
546 this.#currentRefetchInterval === 0 ||
547 !this.#shouldScheduleTimer(this.#currentRefetchInterval)
548 ) {
549 return
550 }
551β
552 this.#refetchIntervalId = timeoutManager.setInterval(() => {
553 if (
554 this.options.refetchIntervalInBackground ||
555 focusManager.isFocused()
556 ) {
557 this.#executeFetch()
558 }
559 }, this.#currentRefetchInterval)
560 }
561β
562 #updateTimers(): void {
563 this.#updateStaleTimeout()
564 this.#updateRefetchInterval(this.#computeRefetchInterval())
565 }
566β
567 #clearStaleTimeout(): void {
568 if (this.#staleTimeoutId !== undefined) {
569 timeoutManager.clearTimeout(this.#staleTimeoutId)
570 this.#staleTimeoutId = undefined
571 }
572 }
573β
574 #clearRefetchInterval(): void {
575 if (this.#refetchIntervalId !== undefined) {
576 timeoutManager.clearInterval(this.#refetchIntervalId)
577 this.#refetchIntervalId = undefined
578 }
579 }
580β
581 /**
582 * Computes the result for a query and options from the query's state, applying `select`,
583 * `placeholderData`, and the derived flags. Subclasses override it to add their own fields.
584 * @param query - The query to compute the result for.
585 * @param options - The observer options to compute the result with.
586 * @returns The computed result.
587 */
588 protected createResult(
589 query: Query<TQueryFnData, TError, TQueryData, TQueryKey>,
590 options: QueryObserverOptions<
591 TQueryFnData,
592 TError,
593 TData,
594 TQueryData,
595 TQueryKey
596 >,
597 ): QueryObserverResult<TData, TError> {
598 const prevQuery = this.#currentQuery
599 const prevOptions = this.options
600 const prevResult = this.#currentResult as
601 | QueryObserverResult<TData, TError>
602 | undefined
603 const prevResultOptions = this.#currentResultOptions
604 const queryChange = query !== prevQuery
605 const queryInitialState = queryChange
606 ? query.state
607 : this.#currentQueryInitialState
608β
609 const { state } = query
610 let newState = { ...state }
611 let isPlaceholderData = false
612 let data: TData | undefined
613β
614 // Optimistically set result in fetching state if needed
615 if (options._optimisticResults) {
616 const mounted = this.hasListeners()
617β
618 const fetchOnMount = !mounted && shouldFetchOnMount(query, options)
619β
620 const fetchOptionally =
621 mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions)
622β
623 if (fetchOnMount || fetchOptionally) {
624 newState = {
625 ...newState,
626 ...fetchState(state.data, query.options),
627 }
628 }
629 if (options._optimisticResults === 'isRestoring') {
630 newState.fetchStatus = 'idle'
631 }
632 }
633β
634 let { error, errorUpdatedAt, status } = newState
635β
636 // Per default, use query data
637 data = newState.data as unknown as TData
638 let skipSelect = false
639β
640 // use placeholderData if needed
641 if (
642 options.placeholderData !== undefined &&
643 data === undefined &&
644 status === 'pending'
645 ) {
646 let placeholderData
647β
648 // Memoize placeholder data
649 const isMemoizedPlaceholder =
650 prevResult?.isPlaceholderData &&
651 options.placeholderData === prevResultOptions?.placeholderData
652 if (isMemoizedPlaceholder) {
653 placeholderData = prevResult.data
654 // we have to skip select when reading this memoization
655 // because prevResult.data is already "selected"
656 skipSelect = true
657 } else {
658 // compute placeholderData
659 placeholderData =
660 typeof options.placeholderData === 'function'
661 ? (
662 options.placeholderData as unknown as PlaceholderDataFunction<TQueryData>
663 )(
664 this.#lastQueryWithDefinedData?.state.data,
665 this.#lastQueryWithDefinedData as any,
666 )
667 : options.placeholderData
668 }
669β
670 // A memoized placeholder stays one even when `select` turned it into undefined
671 if (isMemoizedPlaceholder || placeholderData !== undefined) {
672 status = 'success'
673 data = replaceData(
674 options.select && !skipSelect ? this.#selectInput : prevResult?.data,
675 placeholderData as unknown,
676 options,
677 ) as TData
678 isPlaceholderData = true
679 }
680 }
681β
682 // Select data if needed
683 // this also runs placeholderData through the select function
684 if (options.select && data !== undefined && !skipSelect) {
685 // Memoize select result
686 if (data === this.#selectInput && options.select === this.#selectFn) {
687 data = this.#selectResult
688 } else {
689 try {
690 this.#selectFn = options.select
691 this.#selectInput = data
692 data = options.select(data as unknown as TQueryData)
693 data = replaceData(prevResult?.data, data, options)
694 this.#selectResult = data
695 this.#selectError = null
696 } catch (selectError) {
697 this.#selectError = selectError as TError
698 }
699 }
700 } else if (data === undefined) {
701 // a stored select error belongs to previously selected data; once that
702 // data is gone (query switch or reset), it must not leak into this result
703 this.#selectInput = undefined
704 this.#selectError = null
705 }
706β
707 if (this.#selectError) {
708 error = this.#selectError
709 data = this.#selectResult
710 errorUpdatedAt =
711 prevResult?.error === error ? prevResult.errorUpdatedAt : Date.now()
712 status = 'error'
713 isPlaceholderData = false
714 }
715β
716 const isFetching = newState.fetchStatus === 'fetching'
717 const isPending = status === 'pending'
718 const isError = status === 'error'
719β
720 const isLoading = isPending && isFetching
721 const hasData = data !== undefined
722β
723 const result: QueryObserverBaseResult<TData, TError> = {
724 status,
725 fetchStatus: newState.fetchStatus,
726 isPending,
727 isSuccess: status === 'success',
728 isError,
729 isInitialLoading: isLoading,
730 isLoading,
731 data,
732 dataUpdatedAt: newState.dataUpdatedAt,
733 error,
734 errorUpdatedAt,
735 failureCount: newState.fetchFailureCount,
736 failureReason: newState.fetchFailureReason,
737 errorUpdateCount: newState.errorUpdateCount,
738 isFetched: query.isFetched(),
739 isFetchedAfterMount:
740 newState.dataUpdateCount > queryInitialState.dataUpdateCount ||
741 newState.errorUpdateCount > queryInitialState.errorUpdateCount,
742 isFetching,
743 isRefetching: isFetching && !isPending,
744 isLoadingError: isError && !hasData,
745 isPaused: newState.fetchStatus === 'paused',
746 isPlaceholderData,
747 isRefetchError: isError && hasData,
748 isStale: isStale(query, options),
749 refetch: this.refetch,
750 isEnabled: resolveQueryValue(options.enabled, query) !== false,
751 }
752β
753 const nextResult = result as QueryObserverResult<TData, TError>
754β
755 return nextResult
756 }
757β
758 /**
759 * Recomputes and stores the current result from the current query/options, notifying listeners
760 * if it changed. Framework adapters call this right after subscribing to make sure no query
761 * update was missed in the gap between creating the observer and subscribing to it.
762 */
763 updateResult(): void {
764 const prevResult = this.#currentResult as
765 | QueryObserverResult<TData, TError>
766 | undefined
767β
768 const nextResult = this.createResult(this.#currentQuery, this.options)
769β
770 this.#currentResultOptions = this.options
771β
772 if (this.#currentQuery.state.data !== undefined) {
773 this.#lastQueryWithDefinedData = this.#currentQuery
774 }
775β
776 // Only notify and update result if something has changed
777 if (shallowEqualObjects(nextResult, prevResult)) {
778 return
779 }
780β
781 this.#currentResult = nextResult
782β
783 const shouldNotifyListeners = (): boolean => {
784 if (!prevResult) {
785 return true
786 }
787β
788 const { notifyOnChangeProps } = this.options
789 const notifyOnChangePropsValue =
790 typeof notifyOnChangeProps === 'function'
791 ? notifyOnChangeProps()
792 : notifyOnChangeProps
793β
794 if (
795 notifyOnChangePropsValue === 'all' ||
796 (!notifyOnChangePropsValue && !this.#trackedProps.size)
797 ) {
798 return true
799 }
800β
801 if (
802 this.options.throwOnError &&
803 this.#currentResult.error !== prevResult.error
804 ) {
805 return true
806 }
807β
808 for (const key of notifyOnChangePropsValue ?? this.#trackedProps) {
809 if (
810 this.#currentResult[key as keyof QueryObserverResult] !==
811 prevResult[key as keyof QueryObserverResult]
812 ) {
813 return true
814 }
815 }
816 return false
817 }
818β
819 const notifyListeners = shouldNotifyListeners()
820β
821 notifyManager.batch(() => {
822 // First, trigger the listeners
823 if (notifyListeners) {
824 this.listeners.forEach((listener) => {
825 listener(this.#currentResult)
826 })
827 }
828β
829 // Then the cache listeners
830 this.#client.getQueryCache().notify({
831 query: this.#currentQuery,
832 type: 'observerResultsUpdated',
833 })
834 })
835 }
836β
837 #updateQuery(): void {
838 const query = this.#client.getQueryCache().build(this.#client, this.options)
839β
840 if (query === this.#currentQuery) {
841 return
842 }
843β
844 const prevQuery = this.#currentQuery as
845 | Query<TQueryFnData, TError, TQueryData, TQueryKey>
846 | undefined
847 this.#currentQuery = query
848 this.#currentQueryInitialState = query.state
849β
850 if (this.hasListeners()) {
851 prevQuery?.removeObserver(this)
852 query.addObserver(this)
853 }
854 }
855β
856 /**
857 * Updates the observer's result when the observed query changes, and reschedules its timers if it
858 * has listeners.
859 * @internal
860 */
861 onQueryUpdate(): void {
862 this.updateResult()
863β
864 if (this.hasListeners()) {
865 this.#updateTimers()
866 }
867 }
868}
869β
870/**
871 * Checks whether a query has no data yet and should do its initial load when an observer mounts.
872 * @param query - The query to check.
873 * @param options - The observer options.
874 * @returns `true` if the query is enabled, has no data, and isn't in an error state with
875 * `retryOnMount: false`.
876 */
877function shouldLoadOnMount(
878 query: Query<any, any, any, any>,
879 options: QueryObserverOptions<any, any, any, any>,
880): boolean {
881 return (
882 resolveQueryValue(options.enabled, query) !== false &&
883 query.state.data === undefined &&
884 !(
885 query.state.status === 'error' &&
886 resolveQueryValue(options.retryOnMount, query) === false
887 )
888 )
889}
890β
891/**
892 * Checks whether a query should fetch when an observer mounts: either for its initial load, or
893 * because it has data and `refetchOnMount` asks for a refetch.
894 * @param query - The query to check.
895 * @param options - The observer options.
896 * @returns `true` if the query should fetch on mount.
897 */
898function shouldFetchOnMount(
899 query: Query<any, any, any, any>,
900 options: QueryObserverOptions<any, any, any, any, any>,
901): boolean {
902 return (
903 shouldLoadOnMount(query, options) ||
904 (query.state.data !== undefined &&
905 shouldFetchOn(query, options, options.refetchOnMount))
906 )
907}
908β
909/**
910 * Checks whether a query should fetch for a `refetchOnMount`, `refetchOnWindowFocus`, or
911 * `refetchOnReconnect` option.
912 * @param query - The query to check.
913 * @param options - The observer options.
914 * @param field - The value of the option to check.
915 * @returns `true` if the query is enabled, not static, and the option is `'always'`, or is not
916 * `false` and the query is stale.
917 */
918function shouldFetchOn(
919 query: Query<any, any, any, any>,
920 options: QueryObserverOptions<any, any, any, any, any>,
921 field: (typeof options)['refetchOnMount'] &
922 (typeof options)['refetchOnWindowFocus'] &
923 (typeof options)['refetchOnReconnect'],
924) {
925 if (
926 resolveQueryValue(options.enabled, query) !== false &&
927 resolveQueryValue(options.staleTime, query) !== 'static'
928 ) {
929 const value = resolveQueryValue(field, query)
930β
931 return value === 'always' || (value !== false && isStale(query, options))
932 }
933 return false
934}
935β
936/**
937 * Checks whether a query should fetch after the observer's options change.
938 * @param query - The query observed with the new options.
939 * @param prevQuery - The query observed with the previous options.
940 * @param options - The new observer options.
941 * @param prevOptions - The previous observer options.
942 * @returns `true` if the query changed or was disabled before, it isn't a suspense query in an
943 * error state, and it is stale.
944 */
945function shouldFetchOptionally(
946 query: Query<any, any, any, any>,
947 prevQuery: Query<any, any, any, any>,
948 options: QueryObserverOptions<any, any, any, any, any>,
949 prevOptions: QueryObserverOptions<any, any, any, any, any>,
950): boolean {
951 return (
952 (query !== prevQuery ||
953 resolveQueryValue(prevOptions.enabled, query) === false) &&
954 (!options.suspense || query.state.status !== 'error') &&
955 isStale(query, options)
956 )
957}
958β
959/**
960 * Checks whether a query is stale for the given observer options.
961 * @param query - The query to check.
962 * @param options - The observer options, whose `enabled` and `staleTime` are used.
963 * @returns `true` if the query is enabled and its data is stale for `staleTime`.
964 */
965function isStale(
966 query: Query<any, any, any, any>,
967 options: QueryObserverOptions<any, any, any, any, any>,
968): boolean {
969 return (
970 resolveQueryValue(options.enabled, query) !== false &&
971 query.isStaleByTime(resolveQueryValue(options.staleTime, query))
972 )
973}