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