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