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

queryObserver.ts

902 lines26.1 KB

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