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