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