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

queryObserver.ts

842 lines23.3 KB

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