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