Open History to see the last commit
1import { focusManager } from './focusManager'
2import { isServer as isServerEnvironment } from './environmentManager'
3import { notifyManager } from './notifyManager'
4import { fetchState } from './query'
5import { Subscribable } from './subscribable'
6import {
7 isValidTimeout,
8 noop,
9 replaceData,
10 resolveQueryValue,
11 shallowEqualObjects,
12 timeUntilStale,
13} from './utils'
14import { timeoutManager } from './timeoutManager'
15import type { ManagedTimerId } from './timeoutManager'
16import type { FetchOptions, Query, QueryState } from './query'
17import type { QueryClient } from './queryClient'
18import type {
19 DefaultError,
20 DefaultedQueryObserverOptions,
21 PlaceholderDataFunction,
22 QueryKey,
23 QueryObserverBaseResult,
24 QueryObserverOptions,
25 QueryObserverResult,
26 RefetchOptions,
27} from './types'
28β
29type QueryObserverListener<TData, TError> = (
30 result: QueryObserverResult<TData, TError>,
31) => void
32β
33interface ObserverFetchOptions extends FetchOptions {
34 throwOnError?: boolean
35}
36β
37export class QueryObserver<
38 TQueryFnData = unknown,
39 TError = DefaultError,
40 TData = TQueryFnData,
41 TQueryData = TQueryFnData,
42 TQueryKey extends QueryKey = QueryKey,
43> extends Subscribable<QueryObserverListener<TData, TError>> {
44 #client: QueryClient
45 #currentQuery: Query<TQueryFnData, TError, TQueryData, TQueryKey> = undefined!
46 #currentQueryInitialState: QueryState<TQueryData, TError> = undefined!
47 #currentResult: QueryObserverResult<TData, TError> = undefined!
48 #currentResultState?: QueryState<TQueryData, TError>
49 #currentResultOptions?: QueryObserverOptions<
50 TQueryFnData,
51 TError,
52 TData,
53 TQueryData,
54 TQueryKey
55 >
56 #selectError: TError | null
57 #selectFn?: (data: TQueryData) => TData
58 #selectResult?: TData
59 // This property keeps track of the last query with defined data.
60 // It will be used to pass the previous data and query to the placeholder function between renders.
61 #lastQueryWithDefinedData?: Query<TQueryFnData, TError, TQueryData, TQueryKey>
62 #staleTimeoutId?: ManagedTimerId
63 #refetchIntervalId?: ManagedTimerId
64 #currentRefetchInterval?: number | false
65 #trackedProps = new Set<keyof QueryObserverResult>()
66β
67 constructor(
68 client: QueryClient,
69 public options: QueryObserverOptions<
70 TQueryFnData,
71 TError,
72 TData,
73 TQueryData,
74 TQueryKey
75 >,
76 ) {
77 super()
78β
79 this.#client = client
80 this.#selectError = null
81β
82 this.bindMethods()
83 this.setOptions(options)
84 }
85β
86 protected bindMethods(): void {
87 this.refetch = this.refetch.bind(this)
88 }
89β
90 protected onSubscribe(): void {
91 if (this.listeners.size === 1) {
92 this.#currentQuery.addObserver(this)
93β
94 if (shouldFetchOnMount(this.#currentQuery, this.options)) {
95 this.#executeFetch()
96 } else {
97 this.updateResult()
98 }
99β
100 this.#updateTimers()
101 }
102 }
103β
104 protected onUnsubscribe(): void {
105 if (!this.hasListeners()) {
106 this.destroy()
107 }
108 }
109β
110 shouldFetchOnReconnect(): boolean {
111 return shouldFetchOn(
112 this.#currentQuery,
113 this.options,
114 this.options.refetchOnReconnect,
115 )
116 }
117β
118 shouldFetchOnWindowFocus(): boolean {
119 return shouldFetchOn(
120 this.#currentQuery,
121 this.options,
122 this.options.refetchOnWindowFocus,
123 )
124 }
125β
126 destroy(): void {
127 this.listeners = new Set()
128 this.#clearStaleTimeout()
129 this.#clearRefetchInterval()
130 this.#currentQuery.removeObserver(this)
131 }
132β
133 setOptions(
134 options: QueryObserverOptions<
135 TQueryFnData,
136 TError,
137 TData,
138 TQueryData,
139 TQueryKey
140 >,
141 ): void {
142 const prevOptions = this.options
143 const prevQuery = this.#currentQuery
144β
145 this.options = this.#client.defaultQueryOptions(options)
146β
147 if (
148 this.options.enabled !== undefined &&
149 typeof this.options.enabled !== 'boolean' &&
150 typeof this.options.enabled !== 'function' &&
151 typeof resolveQueryValue(this.options.enabled, this.#currentQuery) !==
152 'boolean'
153 ) {
154 throw new Error(
155 'Expected enabled to be a boolean or a callback that returns a boolean',
156 )
157 }
158β
159 this.#updateQuery()
160 this.#currentQuery.setOptions(this.options)
161β
162 if (
163 prevOptions._defaulted &&
164 !shallowEqualObjects(this.options, prevOptions)
165 ) {
166 this.#client.getQueryCache().notify({
167 type: 'observerOptionsUpdated',
168 query: this.#currentQuery,
169 observer: this,
170 })
171 }
172β
173 const mounted = this.hasListeners()
174β
175 // Fetch if there are subscribers
176 if (
177 mounted &&
178 shouldFetchOptionally(
179 this.#currentQuery,
180 prevQuery,
181 this.options,
182 prevOptions,
183 )
184 ) {
185 this.#executeFetch()
186 }
187β
188 // Update result
189 this.updateResult()
190β
191 // Update stale interval if needed
192 if (
193 mounted &&
194 (this.#currentQuery !== prevQuery ||
195 resolveQueryValue(this.options.enabled, this.#currentQuery) !==
196 resolveQueryValue(prevOptions.enabled, this.#currentQuery) ||
197 resolveQueryValue(this.options.staleTime, this.#currentQuery) !==
198 resolveQueryValue(prevOptions.staleTime, this.#currentQuery))
199 ) {
200 this.#updateStaleTimeout()
201 }
202β
203 const nextRefetchInterval = this.#computeRefetchInterval()
204β
205 // Update refetch interval if needed
206 if (
207 mounted &&
208 (this.#currentQuery !== prevQuery ||
209 resolveQueryValue(this.options.enabled, this.#currentQuery) !==
210 resolveQueryValue(prevOptions.enabled, this.#currentQuery) ||
211 nextRefetchInterval !== this.#currentRefetchInterval)
212 ) {
213 this.#updateRefetchInterval(nextRefetchInterval)
214 }
215 }
216β
217 getOptimisticResult(
218 options: DefaultedQueryObserverOptions<
219 TQueryFnData,
220 TError,
221 TData,
222 TQueryData,
223 TQueryKey
224 >,
225 ): QueryObserverResult<TData, TError> {
226 const query = this.#client.getQueryCache().build(this.#client, options)
227β
228 const result = this.createResult(query, options)
229β
230 if (!shallowEqualObjects(this.getCurrentResult(), result)) {
231 // this assigns the optimistic result to the current Observer
232 // because if the query function changes, useQuery will be performing
233 // an effect where it would fetch again.
234 // When the fetch finishes, we perform a deep data cloning in order
235 // to reuse objects references. This deep data clone is performed against
236 // the `observer.currentResult.data` property
237 // When QueryKey changes, we refresh the query and get new `optimistic`
238 // result, while we leave the `observer.currentResult`, so when new data
239 // arrives, it finds the old `observer.currentResult` which is related
240 // to the old QueryKey. Which means that currentResult and selectData are
241 // out of sync already.
242 // To solve this, we move the cursor of the currentResult every time
243 // an observer reads an optimistic value.
244β
245 // When keeping the previous data, the result doesn't change until new
246 // data arrives.
247 this.#currentResult = result
248 this.#currentResultOptions = this.options
249 this.#currentResultState = this.#currentQuery.state
250 }
251 return result
252 }
253β
254 getCurrentResult(): QueryObserverResult<TData, TError> {
255 return this.#currentResult
256 }
257β
258 trackResult(
259 result: QueryObserverResult<TData, TError>,
260 onPropTracked?: (key: keyof QueryObserverResult) => void,
261 ): QueryObserverResult<TData, TError> {
262 return new Proxy(result, {
263 get: (target, key) => {
264 this.trackProp(key as keyof QueryObserverResult)
265 onPropTracked?.(key as keyof QueryObserverResult)
266 return Reflect.get(target, key)
267 },
268 })
269 }
270β
271 trackProp(key: keyof QueryObserverResult) {
272 this.#trackedProps.add(key)
273 }
274β
275 getCurrentQuery(): Query<TQueryFnData, TError, TQueryData, TQueryKey> {
276 return this.#currentQuery
277 }
278β
279 refetch({ ...options }: RefetchOptions = {}): Promise<
280 QueryObserverResult<TData, TError>
281 > {
282 return this.fetch({
283 ...options,
284 })
285 }
286β
287 fetchOptimistic(
288 options: QueryObserverOptions<
289 TQueryFnData,
290 TError,
291 TData,
292 TQueryData,
293 TQueryKey
294 >,
295 ): Promise<QueryObserverResult<TData, TError>> {
296 const defaultedOptions = this.#client.defaultQueryOptions(options)
297β
298 const query = this.#client
299 .getQueryCache()
300 .build(this.#client, defaultedOptions)
301β
302 let unsubscribe = () => {}
303 let resolveEarly:
304 | ((result: QueryObserverResult<TData, TError>) => void)
305 | undefined
306β
307 const cachePromise = new Promise<QueryObserverResult<TData, TError>>(
308 (resolve) => {
309 resolveEarly = resolve
310 unsubscribe = this.#client.getQueryCache().subscribe((event) => {
311 if (
312 event.type === 'updated' &&
313 event.query.queryHash === query.queryHash &&
314 query.state.data !== undefined
315 ) {
316 unsubscribe()
317 resolve(this.createResult(query, defaultedOptions))
318 }
319 })
320 },
321 )
322β
323 return Promise.race([
324 query
325 .fetch()
326 .then(() => {
327 const result = this.createResult(query, defaultedOptions)
328 // Settle the subscriber promise so both branches always settle.
329 // This value is ignored by Promise.race since the fetch branch already won.
330 resolveEarly?.(result)
331 return result
332 })
333 .finally(() => {
334 unsubscribe()
335 }),
336 cachePromise,
337 ])
338 }
339β
340 protected fetch(
341 fetchOptions: ObserverFetchOptions,
342 ): Promise<QueryObserverResult<TData, TError>> {
343 return this.#executeFetch({
344 ...fetchOptions,
345 cancelRefetch: fetchOptions.cancelRefetch ?? true,
346 }).then(() => {
347 this.updateResult()
348 return this.#currentResult
349 })
350 }
351β
352 #executeFetch(
353 fetchOptions?: Omit<ObserverFetchOptions, 'initialPromise'>,
354 ): Promise<TQueryData | undefined> {
355 // Make sure we reference the latest query as the current one might have been removed
356 this.#updateQuery()
357β
358 // Fetch
359 let promise: Promise<TQueryData | undefined> = this.#currentQuery.fetch(
360 this.options,
361 fetchOptions,
362 )
363β
364 if (!fetchOptions?.throwOnError) {
365 promise = promise.catch(noop)
366 }
367β
368 return promise
369 }
370β
371 #shouldScheduleTimer(timeout: unknown): timeout is number {
372 return (
373 !isServerEnvironment() &&
374 resolveQueryValue(this.options.enabled, this.#currentQuery) !== false &&
375 isValidTimeout(timeout)
376 )
377 }
378β
379 #updateStaleTimeout(): void {
380 this.#clearStaleTimeout()
381 const staleTime = resolveQueryValue(
382 this.options.staleTime,
383 this.#currentQuery,
384 )
385β
386 if (this.#currentResult.isStale || !this.#shouldScheduleTimer(staleTime)) {
387 return
388 }
389β
390 const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime)
391β
392 // The timeout is sometimes triggered 1 ms before the stale time expiration.
393 // To mitigate this issue we always add 1 ms to the timeout.
394 const timeout = time + 1
395β
396 this.#staleTimeoutId = timeoutManager.setTimeout(() => {
397 if (!this.#currentResult.isStale) {
398 this.updateResult()
399 }
400 }, timeout)
401 }
402β
403 #computeRefetchInterval() {
404 return (
405 resolveQueryValue(this.options.refetchInterval, this.#currentQuery) ??
406 false
407 )
408 }
409β
410 #updateRefetchInterval(nextInterval: number | false): void {
411 this.#clearRefetchInterval()
412β
413 this.#currentRefetchInterval = nextInterval
414β
415 if (
416 this.#currentRefetchInterval === 0 ||
417 !this.#shouldScheduleTimer(this.#currentRefetchInterval)
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: resolveQueryValue(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 const notifyListeners = shouldNotifyListeners()
678β
679 notifyManager.batch(() => {
680 // First, trigger the listeners
681 if (notifyListeners) {
682 this.listeners.forEach((listener) => {
683 listener(this.#currentResult)
684 })
685 }
686β
687 // Then the cache listeners
688 this.#client.getQueryCache().notify({
689 query: this.#currentQuery,
690 type: 'observerResultsUpdated',
691 })
692 })
693 }
694β
695 #updateQuery(): void {
696 const query = this.#client.getQueryCache().build(this.#client, this.options)
697β
698 if (query === this.#currentQuery) {
699 return
700 }
701β
702 const prevQuery = this.#currentQuery as
703 | Query<TQueryFnData, TError, TQueryData, TQueryKey>
704 | undefined
705 this.#currentQuery = query
706 this.#currentQueryInitialState = query.state
707β
708 if (this.hasListeners()) {
709 prevQuery?.removeObserver(this)
710 query.addObserver(this)
711 }
712 }
713β
714 onQueryUpdate(): void {
715 this.updateResult()
716β
717 if (this.hasListeners()) {
718 this.#updateTimers()
719 }
720 }
721}
722β
723function shouldLoadOnMount(
724 query: Query<any, any, any, any>,
725 options: QueryObserverOptions<any, any, any, any>,
726): boolean {
727 return (
728 resolveQueryValue(options.enabled, query) !== false &&
729 query.state.data === undefined &&
730 !(
731 query.state.status === 'error' &&
732 resolveQueryValue(options.retryOnMount, query) === false
733 )
734 )
735}
736β
737function shouldFetchOnMount(
738 query: Query<any, any, any, any>,
739 options: QueryObserverOptions<any, any, any, any, any>,
740): boolean {
741 return (
742 shouldLoadOnMount(query, options) ||
743 (query.state.data !== undefined &&
744 shouldFetchOn(query, options, options.refetchOnMount))
745 )
746}
747β
748function shouldFetchOn(
749 query: Query<any, any, any, any>,
750 options: QueryObserverOptions<any, any, any, any, any>,
751 field: (typeof options)['refetchOnMount'] &
752 (typeof options)['refetchOnWindowFocus'] &
753 (typeof options)['refetchOnReconnect'],
754) {
755 if (
756 resolveQueryValue(options.enabled, query) !== false &&
757 resolveQueryValue(options.staleTime, query) !== 'static'
758 ) {
759 const value = resolveQueryValue(field, query)
760β
761 return value === 'always' || (value !== false && isStale(query, options))
762 }
763 return false
764}
765β
766function shouldFetchOptionally(
767 query: Query<any, any, any, any>,
768 prevQuery: Query<any, any, any, any>,
769 options: QueryObserverOptions<any, any, any, any, any>,
770 prevOptions: QueryObserverOptions<any, any, any, any, any>,
771): boolean {
772 return (
773 (query !== prevQuery ||
774 resolveQueryValue(prevOptions.enabled, query) === false) &&
775 (!options.suspense || query.state.status !== 'error') &&
776 isStale(query, options)
777 )
778}
779β
780function isStale(
781 query: Query<any, any, any, any>,
782 options: QueryObserverOptions<any, any, any, any, any>,
783): boolean {
784 return (
785 resolveQueryValue(options.enabled, query) !== false &&
786 query.isStaleByTime(resolveQueryValue(options.staleTime, query))
787 )
788}