Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

queryObserver.ts

803 lines20.7 KB

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