Open History to see the last commit
1import { 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 placeholderData = replaceData(
521 prevResult?.data,
522 placeholderData,
523 options,
524 )
525 this.selectError = null
526 } catch (selectError) {
527 if (process.env.NODE_ENV !== 'production') {
528 this.client.getLogger().error(selectError)
529 }
530 this.selectError = selectError as TError
531 }
532 }
533 }
534β
535 if (typeof placeholderData !== 'undefined') {
536 status = 'success'
537 data = placeholderData as TData
538 isPlaceholderData = true
539 }
540 }
541β
542 if (this.selectError) {
543 error = this.selectError as any
544 data = this.selectResult
545 errorUpdatedAt = Date.now()
546 status = 'error'
547 }
548β
549 const isFetching = fetchStatus === 'fetching'
550β
551 const result: QueryObserverBaseResult<TData, TError> = {
552 status,
553 fetchStatus,
554 isLoading: status === 'loading',
555 isSuccess: status === 'success',
556 isError: status === 'error',
557 data,
558 dataUpdatedAt,
559 error,
560 errorUpdatedAt,
561 failureCount: state.fetchFailureCount,
562 errorUpdateCount: state.errorUpdateCount,
563 isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
564 isFetchedAfterMount:
565 state.dataUpdateCount > queryInitialState.dataUpdateCount ||
566 state.errorUpdateCount > queryInitialState.errorUpdateCount,
567 isFetching: isFetching,
568 isRefetching: isFetching && status !== 'loading',
569 isLoadingError: status === 'error' && state.dataUpdatedAt === 0,
570 isPaused: fetchStatus === 'paused',
571 isPlaceholderData,
572 isPreviousData,
573 isRefetchError: status === 'error' && state.dataUpdatedAt !== 0,
574 isStale: isStale(query, options),
575 refetch: this.refetch,
576 remove: this.remove,
577 }
578β
579 return result as QueryObserverResult<TData, TError>
580 }
581β
582 updateResult(notifyOptions?: NotifyOptions): void {
583 const prevResult = this.currentResult as
584 | QueryObserverResult<TData, TError>
585 | undefined
586β
587 const nextResult = this.createResult(this.currentQuery, this.options)
588 this.currentResultState = this.currentQuery.state
589 this.currentResultOptions = this.options
590β
591 // Only notify and update result if something has changed
592 if (shallowEqualObjects(nextResult, prevResult)) {
593 return
594 }
595β
596 this.currentResult = nextResult
597β
598 // Determine which callbacks to trigger
599 const defaultNotifyOptions: NotifyOptions = { cache: true }
600β
601 const shouldNotifyListeners = (): boolean => {
602 if (!prevResult) {
603 return true
604 }
605β
606 const { notifyOnChangeProps } = this.options
607β
608 if (
609 notifyOnChangeProps === 'all' ||
610 (!notifyOnChangeProps && !this.trackedProps.size)
611 ) {
612 return true
613 }
614β
615 const includedProps = new Set(notifyOnChangeProps ?? this.trackedProps)
616β
617 if (this.options.useErrorBoundary) {
618 includedProps.add('error')
619 }
620β
621 return Object.keys(this.currentResult).some((key) => {
622 const typedKey = key as keyof QueryObserverResult
623 const changed = this.currentResult[typedKey] !== prevResult[typedKey]
624 return changed && includedProps.has(typedKey)
625 })
626 }
627β
628 if (notifyOptions?.listeners !== false && shouldNotifyListeners()) {
629 defaultNotifyOptions.listeners = true
630 }
631β
632 this.notify({ ...defaultNotifyOptions, ...notifyOptions })
633 }
634β
635 private updateQuery(): void {
636 const query = this.client.getQueryCache().build(this.client, this.options)
637β
638 if (query === this.currentQuery) {
639 return
640 }
641β
642 const prevQuery = this.currentQuery as
643 | Query<TQueryFnData, TError, TQueryData, TQueryKey>
644 | undefined
645 this.currentQuery = query
646 this.currentQueryInitialState = query.state
647 this.previousQueryResult = this.currentResult
648β
649 if (this.hasListeners()) {
650 prevQuery?.removeObserver(this)
651 query.addObserver(this)
652 }
653 }
654β
655 onQueryUpdate(action: Action<TData, TError>): void {
656 const notifyOptions: NotifyOptions = {}
657β
658 if (action.type === 'success') {
659 notifyOptions.onSuccess = !action.manual
660 } else if (action.type === 'error' && !isCancelledError(action.error)) {
661 notifyOptions.onError = true
662 }
663β
664 this.updateResult(notifyOptions)
665β
666 if (this.hasListeners()) {
667 this.updateTimers()
668 }
669 }
670β
671 private notify(notifyOptions: NotifyOptions): void {
672 notifyManager.batch(() => {
673 // First trigger the configuration callbacks
674 if (notifyOptions.onSuccess) {
675 this.options.onSuccess?.(this.currentResult.data!)
676 this.options.onSettled?.(this.currentResult.data!, null)
677 } else if (notifyOptions.onError) {
678 this.options.onError?.(this.currentResult.error!)
679 this.options.onSettled?.(undefined, this.currentResult.error!)
680 }
681β
682 // Then trigger the listeners
683 if (notifyOptions.listeners) {
684 this.listeners.forEach((listener) => {
685 listener(this.currentResult)
686 })
687 }
688β
689 // Then the cache listeners
690 if (notifyOptions.cache) {
691 this.client.getQueryCache().notify({
692 query: this.currentQuery,
693 type: 'observerResultsUpdated',
694 })
695 }
696 })
697 }
698}
699β
700function shouldLoadOnMount(
701 query: Query<any, any, any, any>,
702 options: QueryObserverOptions<any, any, any, any>,
703): boolean {
704 return (
705 options.enabled !== false &&
706 !query.state.dataUpdatedAt &&
707 !(query.state.status === 'error' && options.retryOnMount === false)
708 )
709}
710β
711function shouldFetchOnMount(
712 query: Query<any, any, any, any>,
713 options: QueryObserverOptions<any, any, any, any, any>,
714): boolean {
715 return (
716 shouldLoadOnMount(query, options) ||
717 (query.state.dataUpdatedAt > 0 &&
718 shouldFetchOn(query, options, options.refetchOnMount))
719 )
720}
721β
722function shouldFetchOn(
723 query: Query<any, any, any, any>,
724 options: QueryObserverOptions<any, any, any, any, any>,
725 field: typeof options['refetchOnMount'] &
726 typeof options['refetchOnWindowFocus'] &
727 typeof options['refetchOnReconnect'],
728) {
729 if (options.enabled !== false) {
730 const value = typeof field === 'function' ? field(query) : field
731β
732 return value === 'always' || (value !== false && isStale(query, options))
733 }
734 return false
735}
736β
737function shouldFetchOptionally(
738 query: Query<any, any, any, any>,
739 prevQuery: Query<any, any, any, any>,
740 options: QueryObserverOptions<any, any, any, any, any>,
741 prevOptions: QueryObserverOptions<any, any, any, any, any>,
742): boolean {
743 return (
744 options.enabled !== false &&
745 (query !== prevQuery || prevOptions.enabled === false) &&
746 (!options.suspense || query.state.status !== 'error') &&
747 isStale(query, options)
748 )
749}
750β
751function isStale(
752 query: Query<any, any, any, any>,
753 options: QueryObserverOptions<any, any, any, any, any>,
754): boolean {
755 return query.isStaleByTime(options.staleTime)
756}