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