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 isEnabled: resolveEnabled(options.enabled, query) !== false,
580 }
581
582 const nextResult = result as QueryObserverResult<TData, TError>
583
584 if (this.options.experimental_prefetchInRender) {
585 const finalizeThenableIfPossible = (thenable: PendingThenable<TData>) => {
586 if (nextResult.status === 'error') {
587 thenable.reject(nextResult.error)
588 } else if (nextResult.data !== undefined) {
589 thenable.resolve(nextResult.data)
590 }
591 }
592
593 /**
594 * Create a new thenable and result promise when the results have changed
595 */
596 const recreateThenable = () => {
597 const pending =
598 (this.#currentThenable =
599 nextResult.promise =
600 pendingThenable())
601
602 finalizeThenableIfPossible(pending)
603 }
604
605 const prevThenable = this.#currentThenable
606 switch (prevThenable.status) {
607 case 'pending':
608 // Finalize the previous thenable if it was pending
609 // and we are still observing the same query
610 if (query.queryHash === prevQuery.queryHash) {
611 finalizeThenableIfPossible(prevThenable)
612 }
613 break
614 case 'fulfilled':
615 if (
616 nextResult.status === 'error' ||
617 nextResult.data !== prevThenable.value
618 ) {
619 recreateThenable()
620 }
621 break
622 case 'rejected':
623 if (
624 nextResult.status !== 'error' ||
625 nextResult.error !== prevThenable.reason
626 ) {
627 recreateThenable()
628 }
629 break
630 }
631 }
632
633 return nextResult
634 }
635
636 updateResult(): void {
637 const prevResult = this.#currentResult as
638 | QueryObserverResult<TData, TError>
639 | undefined
640
641 const nextResult = this.createResult(this.#currentQuery, this.options)
642
643 this.#currentResultState = this.#currentQuery.state
644 this.#currentResultOptions = this.options
645
646 if (this.#currentResultState.data !== undefined) {
647 this.#lastQueryWithDefinedData = this.#currentQuery
648 }
649
650 // Only notify and update result if something has changed
651 if (shallowEqualObjects(nextResult, prevResult)) {
652 return
653 }
654
655 this.#currentResult = nextResult
656
657 const shouldNotifyListeners = (): boolean => {
658 if (!prevResult) {
659 return true
660 }
661
662 const { notifyOnChangeProps } = this.options
663 const notifyOnChangePropsValue =
664 typeof notifyOnChangeProps === 'function'
665 ? notifyOnChangeProps()
666 : notifyOnChangeProps
667
668 if (
669 notifyOnChangePropsValue === 'all' ||
670 (!notifyOnChangePropsValue && !this.#trackedProps.size)
671 ) {
672 return true
673 }
674
675 const includedProps = new Set(
676 notifyOnChangePropsValue ?? this.#trackedProps,
677 )
678
679 if (this.options.throwOnError) {
680 includedProps.add('error')
681 }
682
683 return Object.keys(this.#currentResult).some((key) => {
684 const typedKey = key as keyof QueryObserverResult
685 const changed = this.#currentResult[typedKey] !== prevResult[typedKey]
686
687 return changed && includedProps.has(typedKey)
688 })
689 }
690
691 this.#notify({ listeners: shouldNotifyListeners() })
692 }
693
694 #updateQuery(): void {
695 const query = this.#client.getQueryCache().build(this.#client, this.options)
696
697 if (query === this.#currentQuery) {
698 return
699 }
700
701 const prevQuery = this.#currentQuery as
702 | Query<TQueryFnData, TError, TQueryData, TQueryKey>
703 | undefined
704 this.#currentQuery = query
705 this.#currentQueryInitialState = query.state
706
707 if (this.hasListeners()) {
708 prevQuery?.removeObserver(this)
709 query.addObserver(this)
710 }
711 }
712
713 onQueryUpdate(): void {
714 this.updateResult()
715
716 if (this.hasListeners()) {
717 this.#updateTimers()
718 }
719 }
720
721 #notify(notifyOptions: { listeners: boolean }): void {
722 notifyManager.batch(() => {
723 // First, trigger the listeners
724 if (notifyOptions.listeners) {
725 this.listeners.forEach((listener) => {
726 listener(this.#currentResult)
727 })
728 }
729
730 // Then the cache listeners
731 this.#client.getQueryCache().notify({
732 query: this.#currentQuery,
733 type: 'observerResultsUpdated',
734 })
735 })
736 }
737}
738
739function shouldLoadOnMount(
740 query: Query<any, any, any, any>,
741 options: QueryObserverOptions<any, any, any, any>,
742): boolean {
743 return (
744 resolveEnabled(options.enabled, query) !== false &&
745 query.state.data === undefined &&
746 !(query.state.status === 'error' && options.retryOnMount === false)
747 )
748}
749
750function shouldFetchOnMount(
751 query: Query<any, any, any, any>,
752 options: QueryObserverOptions<any, any, any, any, any>,
753): boolean {
754 return (
755 shouldLoadOnMount(query, options) ||
756 (query.state.data !== undefined &&
757 shouldFetchOn(query, options, options.refetchOnMount))
758 )
759}
760
761function shouldFetchOn(
762 query: Query<any, any, any, any>,
763 options: QueryObserverOptions<any, any, any, any, any>,
764 field: (typeof options)['refetchOnMount'] &
765 (typeof options)['refetchOnWindowFocus'] &
766 (typeof options)['refetchOnReconnect'],
767) {
768 if (
769 resolveEnabled(options.enabled, query) !== false &&
770 resolveStaleTime(options.staleTime, query) !== 'static'
771 ) {
772 const value = typeof field === 'function' ? field(query) : field
773
774 return value === 'always' || (value !== false && isStale(query, options))
775 }
776 return false
777}
778
779function shouldFetchOptionally(
780 query: Query<any, any, any, any>,
781 prevQuery: Query<any, any, any, any>,
782 options: QueryObserverOptions<any, any, any, any, any>,
783 prevOptions: QueryObserverOptions<any, any, any, any, any>,
784): boolean {
785 return (
786 (query !== prevQuery ||
787 resolveEnabled(prevOptions.enabled, query) === false) &&
788 (!options.suspense || query.state.status !== 'error') &&
789 isStale(query, options)
790 )
791}
792
793function isStale(
794 query: Query<any, any, any, any>,
795 options: QueryObserverOptions<any, any, any, any, any>,
796): boolean {
797 return (
798 resolveEnabled(options.enabled, query) !== false &&
799 query.isStaleByTime(resolveStaleTime(options.staleTime, query))
800 )
801}
802
803// this function would decide if we will update the observer's 'current'
804// properties after an optimistic reading via getOptimisticResult
805function shouldAssignObserverCurrentProperties<
806 TQueryFnData = unknown,
807 TError = unknown,
808 TData = TQueryFnData,
809 TQueryData = TQueryFnData,
810 TQueryKey extends QueryKey = QueryKey,
811>(
812 observer: QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>,
813 optimisticResult: QueryObserverResult<TData, TError>,
814) {
815 // if the newly created result isn't what the observer is holding as current,
816 // then we'll need to update the properties as well
817 if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) {
818 return true
819 }
820
821 // basically, just keep previous properties if nothing changed
822 return false
823}