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

queryObserver.ts

759 lines20.3 KB

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