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