Open History to see the last commit
1import { RefetchQueryFilters } from './types'
2import {
3 isServer,
4 isValidTimeout,
5 noop,
6 replaceEqualDeep,
7 shallowEqualObjects,
8 timeUntilStale,
9} from './utils'
10import { notifyManager } from './notifyManager'
11import type {
12 PlaceholderDataFunction,
13 QueryKey,
14 QueryObserverBaseResult,
15 QueryObserverOptions,
16 QueryObserverResult,
17 QueryOptions,
18 RefetchOptions,
19 ResultOptions,
20} from './types'
21import type { Query, QueryState, Action, FetchOptions } from './query'
22import type { QueryClient } from './queryClient'
23import { focusManager } from './focusManager'
24import { Subscribable } from './subscribable'
25import { getLogger } from './logger'
26import { isCancelledError } from './retryer'
27β
28type QueryObserverListener<TData, TError> = (
29 result: QueryObserverResult<TData, TError>
30) => void
31β
32export interface NotifyOptions {
33 cache?: boolean
34 listeners?: boolean
35 onError?: boolean
36 onSuccess?: boolean
37}
38β
39export interface ObserverFetchOptions extends FetchOptions {
40 throwOnError?: boolean
41}
42β
43export class QueryObserver<
44 TQueryFnData = unknown,
45 TError = unknown,
46 TData = TQueryFnData,
47 TQueryData = TQueryFnData,
48 TQueryKey extends QueryKey = QueryKey
49> extends Subscribable<QueryObserverListener<TData, TError>> {
50 options: QueryObserverOptions<
51 TQueryFnData,
52 TError,
53 TData,
54 TQueryData,
55 TQueryKey
56 >
57β
58 private client: QueryClient
59 private currentQuery!: Query<TQueryFnData, TError, TQueryData, TQueryKey>
60 private currentQueryInitialState!: QueryState<TQueryData, TError>
61 private currentResult!: QueryObserverResult<TData, TError>
62 private currentResultState?: QueryState<TQueryData, TError>
63 private currentResultOptions?: QueryObserverOptions<
64 TQueryFnData,
65 TError,
66 TData,
67 TQueryData,
68 TQueryKey
69 >
70 private previousQueryResult?: QueryObserverResult<TData, TError>
71 private previousSelectError: Error | null
72 private staleTimeoutId?: number
73 private refetchIntervalId?: number
74 private currentRefetchInterval?: number | false
75 private trackedProps!: Array<keyof QueryObserverResult>
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.trackedProps = []
92 this.previousSelectError = null
93 this.bindMethods()
94 this.setOptions(options)
95 }
96β
97 protected bindMethods(): void {
98 this.remove = this.remove.bind(this)
99 this.refetch = this.refetch.bind(this)
100 }
101β
102 protected onSubscribe(): void {
103 if (this.listeners.length === 1) {
104 this.currentQuery.addObserver(this)
105β
106 if (shouldFetchOnMount(this.currentQuery, this.options)) {
107 this.executeFetch()
108 }
109β
110 this.updateTimers()
111 }
112 }
113β
114 protected onUnsubscribe(): void {
115 if (!this.listeners.length) {
116 this.destroy()
117 }
118 }
119β
120 shouldFetchOnReconnect(): boolean {
121 return shouldFetchOnReconnect(this.currentQuery, this.options)
122 }
123β
124 shouldFetchOnWindowFocus(): boolean {
125 return shouldFetchOnWindowFocus(this.currentQuery, this.options)
126 }
127β
128 destroy(): void {
129 this.listeners = []
130 this.clearTimers()
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.defaultQueryObserverOptions(options)
148β
149 if (
150 typeof this.options.enabled !== 'undefined' &&
151 typeof this.options.enabled !== 'boolean'
152 ) {
153 throw new Error('Expected enabled to be a boolean')
154 }
155β
156 // Keep previous query key if the user does not supply one
157 if (!this.options.queryKey) {
158 this.options.queryKey = prevOptions.queryKey
159 }
160β
161 this.updateQuery()
162β
163 const mounted = this.hasListeners()
164β
165 // Fetch if there are subscribers
166 if (
167 mounted &&
168 shouldFetchOptionally(
169 this.currentQuery,
170 prevQuery,
171 this.options,
172 prevOptions
173 )
174 ) {
175 this.executeFetch()
176 }
177β
178 // Update result
179 this.updateResult(notifyOptions)
180β
181 // Update stale interval if needed
182 if (
183 mounted &&
184 (this.currentQuery !== prevQuery ||
185 this.options.enabled !== prevOptions.enabled ||
186 this.options.staleTime !== prevOptions.staleTime)
187 ) {
188 this.updateStaleTimeout()
189 }
190β
191 const nextRefetchInterval = this.computeRefetchInterval()
192β
193 // Update refetch interval if needed
194 if (
195 mounted &&
196 (this.currentQuery !== prevQuery ||
197 this.options.enabled !== prevOptions.enabled ||
198 nextRefetchInterval !== this.currentRefetchInterval)
199 ) {
200 this.updateRefetchInterval(nextRefetchInterval)
201 }
202 }
203β
204 getOptimisticResult(
205 options: QueryObserverOptions<
206 TQueryFnData,
207 TError,
208 TData,
209 TQueryData,
210 TQueryKey
211 >
212 ): QueryObserverResult<TData, TError> {
213 const defaultedOptions = this.client.defaultQueryObserverOptions(options)
214β
215 const query = this.client
216 .getQueryCache()
217 .build(
218 this.client,
219 defaultedOptions as QueryOptions<
220 TQueryFnData,
221 TError,
222 TQueryData,
223 TQueryKey
224 >
225 )
226β
227 return this.createResult(query, defaultedOptions)
228 }
229β
230 getCurrentResult(): QueryObserverResult<TData, TError> {
231 return this.currentResult
232 }
233β
234 trackResult(
235 result: QueryObserverResult<TData, TError>
236 ): QueryObserverResult<TData, TError> {
237 const trackedResult = {} as QueryObserverResult<TData, TError>
238β
239 Object.keys(result).forEach(key => {
240 Object.defineProperty(trackedResult, key, {
241 configurable: false,
242 enumerable: true,
243 get: () => {
244 const typedKey = key as keyof QueryObserverResult
245 if (!this.trackedProps.includes(typedKey)) {
246 this.trackedProps.push(typedKey)
247 }
248 return result[typedKey]
249 },
250 })
251 })
252β
253 return trackedResult
254 }
255β
256 getNextResult(
257 options?: ResultOptions
258 ): Promise<QueryObserverResult<TData, TError>> {
259 return new Promise((resolve, reject) => {
260 const unsubscribe = this.subscribe(result => {
261 if (!result.isFetching) {
262 unsubscribe()
263 if (result.isError && options?.throwOnError) {
264 reject(result.error)
265 } else {
266 resolve(result)
267 }
268 }
269 })
270 })
271 }
272β
273 getCurrentQuery(): Query<TQueryFnData, TError, TQueryData, TQueryKey> {
274 return this.currentQuery
275 }
276β
277 remove(): void {
278 this.client.getQueryCache().remove(this.currentQuery)
279 }
280β
281 refetch<TPageData>(
282 options?: RefetchOptions & RefetchQueryFilters<TPageData>
283 ): Promise<QueryObserverResult<TData, TError>> {
284 return this.fetch({
285 ...options,
286 meta: { refetchPage: options?.refetchPage },
287 })
288 }
289β
290 fetchOptimistic(
291 options: QueryObserverOptions<
292 TQueryFnData,
293 TError,
294 TData,
295 TQueryData,
296 TQueryKey
297 >
298 ): Promise<QueryObserverResult<TData, TError>> {
299 const defaultedOptions = this.client.defaultQueryObserverOptions(options)
300β
301 const query = this.client
302 .getQueryCache()
303 .build(
304 this.client,
305 defaultedOptions as QueryOptions<
306 TQueryFnData,
307 TError,
308 TQueryData,
309 TQueryKey
310 >
311 )
312β
313 return query.fetch().then(() => this.createResult(query, defaultedOptions))
314 }
315β
316 protected fetch(
317 fetchOptions?: ObserverFetchOptions
318 ): Promise<QueryObserverResult<TData, TError>> {
319 return this.executeFetch(fetchOptions).then(() => {
320 this.updateResult()
321 return this.currentResult
322 })
323 }
324β
325 private executeFetch(
326 fetchOptions?: ObserverFetchOptions
327 ): Promise<TQueryData | undefined> {
328 // Make sure we reference the latest query as the current one might have been removed
329 this.updateQuery()
330β
331 // Fetch
332 let promise: Promise<TQueryData | undefined> = this.currentQuery.fetch(
333 this.options as QueryOptions<TQueryFnData, TError, TQueryData, TQueryKey>,
334 fetchOptions
335 )
336β
337 if (!fetchOptions?.throwOnError) {
338 promise = promise.catch(noop)
339 }
340β
341 return promise
342 }
343β
344 private updateStaleTimeout(): void {
345 this.clearStaleTimeout()
346β
347 if (
348 isServer ||
349 this.currentResult.isStale ||
350 !isValidTimeout(this.options.staleTime)
351 ) {
352 return
353 }
354β
355 const time = timeUntilStale(
356 this.currentResult.dataUpdatedAt,
357 this.options.staleTime
358 )
359β
360 // The timeout is sometimes triggered 1 ms before the stale time expiration.
361 // To mitigate this issue we always add 1 ms to the timeout.
362 const timeout = time + 1
363β
364 this.staleTimeoutId = setTimeout(() => {
365 if (!this.currentResult.isStale) {
366 this.updateResult()
367 }
368 }, timeout)
369 }
370β
371 private computeRefetchInterval() {
372 return typeof this.options.refetchInterval === 'function'
373 ? this.options.refetchInterval(this.currentResult.data, this.currentQuery)
374 : this.options.refetchInterval ?? false
375 }
376β
377 private updateRefetchInterval(nextInterval: number | false): void {
378 this.clearRefetchInterval()
379β
380 this.currentRefetchInterval = nextInterval
381β
382 if (
383 isServer ||
384 this.options.enabled === false ||
385 !isValidTimeout(this.currentRefetchInterval) ||
386 this.currentRefetchInterval === 0
387 ) {
388 return
389 }
390β
391 this.refetchIntervalId = setInterval(() => {
392 if (
393 this.options.refetchIntervalInBackground ||
394 focusManager.isFocused()
395 ) {
396 this.executeFetch()
397 }
398 }, this.currentRefetchInterval)
399 }
400β
401 private updateTimers(): void {
402 this.updateStaleTimeout()
403 this.updateRefetchInterval(this.computeRefetchInterval())
404 }
405β
406 private clearTimers(): void {
407 this.clearStaleTimeout()
408 this.clearRefetchInterval()
409 }
410β
411 private clearStaleTimeout(): void {
412 clearTimeout(this.staleTimeoutId)
413 this.staleTimeoutId = undefined
414 }
415β
416 private clearRefetchInterval(): void {
417 clearInterval(this.refetchIntervalId)
418 this.refetchIntervalId = undefined
419 }
420β
421 protected createResult(
422 query: Query<TQueryFnData, TError, TQueryData, TQueryKey>,
423 options: QueryObserverOptions<
424 TQueryFnData,
425 TError,
426 TData,
427 TQueryData,
428 TQueryKey
429 >
430 ): QueryObserverResult<TData, TError> {
431 const prevQuery = this.currentQuery
432 const prevOptions = this.options
433 const prevResult = this.currentResult
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 const prevQueryResult = queryChange
441 ? this.currentResult
442 : this.previousQueryResult
443β
444 const { state } = query
445 let { dataUpdatedAt, error, errorUpdatedAt, isFetching, status } = state
446 let isPreviousData = false
447 let isPlaceholderData = false
448 let data: TData | undefined
449β
450 // Optimistically set result in fetching state if needed
451 if (options.optimisticResults) {
452 const mounted = this.hasListeners()
453β
454 const fetchOnMount = !mounted && shouldFetchOnMount(query, options)
455β
456 const fetchOptionally =
457 mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions)
458β
459 if (fetchOnMount || fetchOptionally) {
460 isFetching = true
461 if (!dataUpdatedAt) {
462 status = 'loading'
463 }
464 }
465 }
466β
467 // Keep previous data if needed
468 if (
469 options.keepPreviousData &&
470 !state.dataUpdateCount &&
471 prevQueryResult?.isSuccess &&
472 status !== 'error'
473 ) {
474 data = prevQueryResult.data
475 dataUpdatedAt = prevQueryResult.dataUpdatedAt
476 status = prevQueryResult.status
477 isPreviousData = true
478 }
479 // Select data if needed
480 else if (options.select && typeof state.data !== 'undefined') {
481 // Memoize select result
482 if (
483 prevResult &&
484 state.data === prevResultState?.data &&
485 options.select === prevResultOptions?.select &&
486 !this.previousSelectError
487 ) {
488 data = prevResult.data
489 } else {
490 try {
491 data = options.select(state.data)
492 if (options.structuralSharing !== false) {
493 data = replaceEqualDeep(prevResult?.data, data)
494 }
495 this.previousSelectError = null
496 } catch (selectError) {
497 getLogger().error(selectError)
498 error = selectError
499 this.previousSelectError = selectError
500 errorUpdatedAt = Date.now()
501 status = 'error'
502 }
503 }
504 }
505 // Use query data
506 else {
507 data = (state.data as unknown) as TData
508 }
509β
510 // Show placeholder data if needed
511 if (
512 typeof options.placeholderData !== 'undefined' &&
513 typeof data === 'undefined' &&
514 (status === 'loading' || status === 'idle')
515 ) {
516 let placeholderData
517β
518 // Memoize placeholder data
519 if (
520 prevResult?.isPlaceholderData &&
521 options.placeholderData === prevResultOptions?.placeholderData
522 ) {
523 placeholderData = prevResult.data
524 } else {
525 placeholderData =
526 typeof options.placeholderData === 'function'
527 ? (options.placeholderData as PlaceholderDataFunction<TQueryData>)()
528 : options.placeholderData
529 if (options.select && typeof placeholderData !== 'undefined') {
530 try {
531 placeholderData = options.select(placeholderData)
532 if (options.structuralSharing !== false) {
533 placeholderData = replaceEqualDeep(
534 prevResult?.data,
535 placeholderData
536 )
537 }
538 this.previousSelectError = null
539 } catch (selectError) {
540 getLogger().error(selectError)
541 error = selectError
542 this.previousSelectError = selectError
543 errorUpdatedAt = Date.now()
544 status = 'error'
545 }
546 }
547 }
548β
549 if (typeof placeholderData !== 'undefined') {
550 status = 'success'
551 data = placeholderData as TData
552 isPlaceholderData = true
553 }
554 }
555β
556 const result: QueryObserverBaseResult<TData, TError> = {
557 status,
558 isLoading: status === 'loading',
559 isSuccess: status === 'success',
560 isError: status === 'error',
561 isIdle: status === 'idle',
562 data,
563 dataUpdatedAt,
564 error,
565 errorUpdatedAt,
566 failureCount: state.fetchFailureCount,
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 && status !== 'loading',
573 isLoadingError: status === 'error' && state.dataUpdatedAt === 0,
574 isPlaceholderData,
575 isPreviousData,
576 isRefetchError: status === 'error' && state.dataUpdatedAt !== 0,
577 isStale: isStale(query, options),
578 refetch: this.refetch,
579 remove: this.remove,
580 }
581β
582 return result as QueryObserverResult<TData, TError>
583 }
584β
585 private shouldNotifyListeners(
586 result: QueryObserverResult,
587 prevResult?: QueryObserverResult
588 ): boolean {
589 if (!prevResult) {
590 return true
591 }
592β
593 if (result === prevResult) {
594 return false
595 }
596β
597 const { notifyOnChangeProps, notifyOnChangePropsExclusions } = this.options
598β
599 if (!notifyOnChangeProps && !notifyOnChangePropsExclusions) {
600 return true
601 }
602β
603 if (notifyOnChangeProps === 'tracked' && !this.trackedProps.length) {
604 return true
605 }
606β
607 const includedProps =
608 notifyOnChangeProps === 'tracked'
609 ? this.trackedProps
610 : notifyOnChangeProps
611β
612 return Object.keys(result).some(key => {
613 const typedKey = key as keyof QueryObserverResult
614 const changed = result[typedKey] !== prevResult[typedKey]
615 const isIncluded = includedProps?.some(x => x === key)
616 const isExcluded = notifyOnChangePropsExclusions?.some(x => x === key)
617 return changed && !isExcluded && (!includedProps || isIncluded)
618 })
619 }
620β
621 updateResult(notifyOptions?: NotifyOptions): void {
622 const prevResult = this.currentResult as
623 | QueryObserverResult<TData, TError>
624 | undefined
625β
626 this.currentResult = this.createResult(this.currentQuery, this.options)
627 this.currentResultState = this.currentQuery.state
628 this.currentResultOptions = this.options
629β
630 // Only notify if something has changed
631 if (shallowEqualObjects(this.currentResult, prevResult)) {
632 return
633 }
634β
635 // Determine which callbacks to trigger
636 const defaultNotifyOptions: NotifyOptions = { cache: true }
637β
638 if (
639 notifyOptions?.listeners !== false &&
640 this.shouldNotifyListeners(this.currentResult, prevResult)
641 ) {
642 defaultNotifyOptions.listeners = true
643 }
644β
645 this.notify({ ...defaultNotifyOptions, ...notifyOptions })
646 }
647β
648 private updateQuery(): void {
649 const query = this.client
650 .getQueryCache()
651 .build(
652 this.client,
653 this.options as QueryOptions<
654 TQueryFnData,
655 TError,
656 TQueryData,
657 TQueryKey
658 >
659 )
660β
661 if (query === this.currentQuery) {
662 return
663 }
664β
665 const prevQuery = this.currentQuery
666 this.currentQuery = query
667 this.currentQueryInitialState = query.state
668 this.previousQueryResult = this.currentResult
669β
670 if (this.hasListeners()) {
671 prevQuery?.removeObserver(this)
672 query.addObserver(this)
673 }
674 }
675β
676 onQueryUpdate(action: Action<TData, TError>): void {
677 const notifyOptions: NotifyOptions = {}
678β
679 if (action.type === 'success') {
680 notifyOptions.onSuccess = true
681 } else if (action.type === 'error' && !isCancelledError(action.error)) {
682 notifyOptions.onError = true
683 }
684β
685 this.updateResult(notifyOptions)
686β
687 if (this.hasListeners()) {
688 this.updateTimers()
689 }
690 }
691β
692 private notify(notifyOptions: NotifyOptions): void {
693 notifyManager.batch(() => {
694 // First trigger the configuration callbacks
695 if (notifyOptions.onSuccess) {
696 this.options.onSuccess?.(this.currentResult.data!)
697 this.options.onSettled?.(this.currentResult.data!, null)
698 } else if (notifyOptions.onError) {
699 this.options.onError?.(this.currentResult.error!)
700 this.options.onSettled?.(undefined, this.currentResult.error!)
701 }
702β
703 // Then trigger the listeners
704 if (notifyOptions.listeners) {
705 this.listeners.forEach(listener => {
706 listener(this.currentResult)
707 })
708 }
709β
710 // Then the cache listeners
711 if (notifyOptions.cache) {
712 this.client
713 .getQueryCache()
714 .notify({ query: this.currentQuery, type: 'observerResultsUpdated' })
715 }
716 })
717 }
718}
719β
720function shouldLoadOnMount(
721 query: Query<any, any, any, any>,
722 options: QueryObserverOptions<any, any, any, any>
723): boolean {
724 return (
725 options.enabled !== false &&
726 !query.state.dataUpdatedAt &&
727 !(query.state.status === 'error' && options.retryOnMount === false)
728 )
729}
730β
731function shouldRefetchOnMount(
732 query: Query<any, any, any, any>,
733 options: QueryObserverOptions<any, any, any, any>
734): boolean {
735 return (
736 options.enabled !== false &&
737 query.state.dataUpdatedAt > 0 &&
738 (options.refetchOnMount === 'always' ||
739 (options.refetchOnMount !== false && isStale(query, options)))
740 )
741}
742β
743function shouldFetchOnMount(
744 query: Query<any, any, any, any>,
745 options: QueryObserverOptions<any, any, any, any, any>
746): boolean {
747 return (
748 shouldLoadOnMount(query, options) || shouldRefetchOnMount(query, options)
749 )
750}
751β
752function shouldFetchOnReconnect(
753 query: Query<any, any, any, any>,
754 options: QueryObserverOptions<any, any, any, any, any>
755): boolean {
756 return (
757 options.enabled !== false &&
758 (options.refetchOnReconnect === 'always' ||
759 (options.refetchOnReconnect !== false && isStale(query, options)))
760 )
761}
762β
763function shouldFetchOnWindowFocus(
764 query: Query<any, any, any, any>,
765 options: QueryObserverOptions<any, any, any, any, any>
766): boolean {
767 return (
768 options.enabled !== false &&
769 (options.refetchOnWindowFocus === 'always' ||
770 (options.refetchOnWindowFocus !== false && isStale(query, options)))
771 )
772}
773β
774function shouldFetchOptionally(
775 query: Query<any, any, any, any>,
776 prevQuery: Query<any, any, any, any>,
777 options: QueryObserverOptions<any, any, any, any, any>,
778 prevOptions: QueryObserverOptions<any, any, any, any, any>
779): boolean {
780 return (
781 options.enabled !== false &&
782 (query !== prevQuery || prevOptions.enabled === false) &&
783 (!options.suspense ||
784 query.state.status !== 'error' ||
785 prevOptions.enabled === false) &&
786 isStale(query, options)
787 )
788}
789β
790function isStale(
791 query: Query<any, any, any, any>,
792 options: QueryObserverOptions<any, any, any, any, any>
793): boolean {
794 return query.isStaleByTime(options.staleTime)
795}