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