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