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

queryObserver.ts

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