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