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

queryObserver.ts

768 lines20.8 KB

1import {
2 isServer,
3 isValidTimeout,
4 noop,
5 replaceData,
6 shallowEqualObjects,
7 timeUntilStale,
8} from './utils'
9import { notifyManager } from './notifyManager'
10import { focusManager } from './focusManager'
11import { Subscribable } from './subscribable'
12import { fetchState } from './query'
13import type { FetchOptions, Query, QueryState } from './query'
14import type { QueryClient } from './queryClient'
15import type {
16 DefaultError,
17 DefaultedQueryObserverOptions,
18 PlaceholderDataFunction,
19 QueryKey,
20 QueryObserverBaseResult,
21 QueryObserverOptions,
22 QueryObserverResult,
23 QueryOptions,
24 RefetchOptions,
25} from './types'
26​
27type QueryObserverListener<TData, TError> = (
28 result: QueryObserverResult<TData, TError>,
29) => void
30​
31export interface NotifyOptions {
32 listeners?: boolean
34​
35export interface ObserverFetchOptions extends FetchOptions {
36 throwOnError?: boolean
38​
39export class QueryObserver<
40 TQueryFnData = unknown,
41 TError = DefaultError,
42 TData = TQueryFnData,
43 TQueryData = TQueryFnData,
44 TQueryKey extends QueryKey = QueryKey,
45> extends Subscribable<QueryObserverListener<TData, TError>> {
46 #client: QueryClient
47 #currentQuery: Query<TQueryFnData, TError, TQueryData, TQueryKey> = undefined!
48 #currentQueryInitialState: QueryState<TQueryData, TError> = undefined!
49 #currentResult: QueryObserverResult<TData, TError> = undefined!
50 #currentResultState?: QueryState<TQueryData, TError>
51 #currentResultOptions?: QueryObserverOptions<
52 TQueryFnData,
53 TError,
54 TData,
55 TQueryData,
56 TQueryKey
57 >
58 #selectError: TError | null
59 #selectFn?: (data: TQueryData) => TData
60 #selectResult?: TData
61 // This property keeps track of the last query with defined data.
62 // It will be used to pass the previous data and query to the placeholder function between renders.
63 #lastQueryWithDefinedData?: Query<TQueryFnData, TError, TQueryData, TQueryKey>
64 #staleTimeoutId?: ReturnType<typeof setTimeout>
65 #refetchIntervalId?: ReturnType<typeof setInterval>
66 #currentRefetchInterval?: number | false
67 #trackedProps = new Set<keyof QueryObserverResult>()
68​
69 constructor(
70 client: QueryClient,
71 public options: QueryObserverOptions<
72 TQueryFnData,
73 TError,
74 TData,
75 TQueryData,
76 TQueryKey
77 >,
78 ) {
79 super()
80​
81 this.#client = client
82 this.#selectError = null
83 this.bindMethods()
84 this.setOptions(options)
85 }
86​
87 protected bindMethods(): void {
88 this.refetch = this.refetch.bind(this)
89 }
90​
91 protected onSubscribe(): void {
92 if (this.listeners.size === 1) {
93 this.#currentQuery.addObserver(this)
94​
95 if (shouldFetchOnMount(this.#currentQuery, this.options)) {
96 this.#executeFetch()
97 } else {
98 this.updateResult()
99 }
100​
101 this.#updateTimers()
102 }
103 }
104​
105 protected onUnsubscribe(): void {
106 if (!this.hasListeners()) {
107 this.destroy()
108 }
109 }
110​
111 shouldFetchOnReconnect(): boolean {
112 return shouldFetchOn(
113 this.#currentQuery,
114 this.options,
115 this.options.refetchOnReconnect,
116 )
117 }
118​
119 shouldFetchOnWindowFocus(): boolean {
120 return shouldFetchOn(
121 this.#currentQuery,
122 this.options,
123 this.options.refetchOnWindowFocus,
124 )
125 }
126​
127 destroy(): void {
128 this.listeners = new Set()
129 this.#clearStaleTimeout()
130 this.#clearRefetchInterval()
131 this.#currentQuery.removeObserver(this)
132 }
133​
134 setOptions(
135 options: QueryObserverOptions<
136 TQueryFnData,
137 TError,
138 TData,
139 TQueryData,
140 TQueryKey
141 >,
142 notifyOptions?: NotifyOptions,
143 ): void {
144 const prevOptions = this.options
145 const prevQuery = this.#currentQuery
146​
147 this.options = this.#client.defaultQueryOptions(options)
148​
149 if (
150 this.options.enabled !== undefined &&
151 typeof this.options.enabled !== 'boolean'
152 ) {
153 throw new Error('Expected enabled to be a boolean')
154 }
155​
156 this.#updateQuery()
157 this.#currentQuery.setOptions(this.options)
158​
159 if (
160 prevOptions._defaulted &&
161 !shallowEqualObjects(this.options, prevOptions)
162 ) {
163 this.#client.getQueryCache().notify({
164 type: 'observerOptionsUpdated',
165 query: this.#currentQuery,
166 observer: this,
167 })
168 }
169​
170 const mounted = this.hasListeners()
171​
172 // Fetch if there are subscribers
173 if (
174 mounted &&
175 shouldFetchOptionally(
176 this.#currentQuery,
177 prevQuery,
178 this.options,
179 prevOptions,
180 )
181 ) {
182 this.#executeFetch()
183 }
184​
185 // Update result
186 this.updateResult(notifyOptions)
187​
188 // Update stale interval if needed
189 if (
190 mounted &&
191 (this.#currentQuery !== prevQuery ||
192 this.options.enabled !== prevOptions.enabled ||
193 this.options.staleTime !== prevOptions.staleTime)
194 ) {
195 this.#updateStaleTimeout()
196 }
197​
198 const nextRefetchInterval = this.#computeRefetchInterval()
199​
200 // Update refetch interval if needed
201 if (
202 mounted &&
203 (this.#currentQuery !== prevQuery ||
204 this.options.enabled !== prevOptions.enabled ||
205 nextRefetchInterval !== this.#currentRefetchInterval)
206 ) {
207 this.#updateRefetchInterval(nextRefetchInterval)
208 }
209 }
210​
211 getOptimisticResult(
212 options: DefaultedQueryObserverOptions<
213 TQueryFnData,
214 TError,
215 TData,
216 TQueryData,
217 TQueryKey
218 >,
219 ): QueryObserverResult<TData, TError> {
220 const query = this.#client.getQueryCache().build(this.#client, options)
221​
222 const result = this.createResult(query, options)
223​
224 if (shouldAssignObserverCurrentProperties(this, result)) {
225 // this assigns the optimistic result to the current Observer
226 // because if the query function changes, useQuery will be performing
227 // an effect where it would fetch again.
228 // When the fetch finishes, we perform a deep data cloning in order
229 // to reuse objects references. This deep data clone is performed against
230 // the `observer.currentResult.data` property
231 // When QueryKey changes, we refresh the query and get new `optimistic`
232 // result, while we leave the `observer.currentResult`, so when new data
233 // arrives, it finds the old `observer.currentResult` which is related
234 // to the old QueryKey. Which means that currentResult and selectData are
235 // out of sync already.
236 // To solve this, we move the cursor of the currentResult every time
237 // an observer reads an optimistic value.
238​
239 // When keeping the previous data, the result doesn't change until new
240 // data arrives.
241 this.#currentResult = result
242 this.#currentResultOptions = this.options
243 this.#currentResultState = this.#currentQuery.state
244 }
245 return result
246 }
247​
248 getCurrentResult(): QueryObserverResult<TData, TError> {
249 return this.#currentResult
250 }
251​
252 trackResult(
253 result: QueryObserverResult<TData, TError>,
254 onPropTracked?: (key: keyof QueryObserverResult) => void,
255 ): QueryObserverResult<TData, TError> {
256 const trackedResult = {} as QueryObserverResult<TData, TError>
257​
258 Object.keys(result).forEach((key) => {
259 Object.defineProperty(trackedResult, key, {
260 configurable: false,
261 enumerable: true,
262 get: () => {
263 this.trackProp(key as keyof QueryObserverResult)
264 onPropTracked?.(key as keyof QueryObserverResult)
265 return result[key as keyof QueryObserverResult]
266 },
267 })
268 })
269​
270 return trackedResult
271 }
272​
273 trackProp(key: keyof QueryObserverResult) {
274 this.#trackedProps.add(key)
275 }
276​
277 getCurrentQuery(): Query<TQueryFnData, TError, TQueryData, TQueryKey> {
278 return this.#currentQuery
279 }
280​
281 refetch({ ...options }: RefetchOptions = {}): Promise<
282 QueryObserverResult<TData, TError>
283 > {
284 return this.fetch({
285 ...options,
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 #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 #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 #computeRefetchInterval() {
367 return (
368 (typeof this.options.refetchInterval === 'function'
369 ? this.options.refetchInterval(this.#currentQuery)
370 : this.options.refetchInterval) ?? false
371 )
372 }
373​
374 #updateRefetchInterval(nextInterval: number | false): void {
375 this.#clearRefetchInterval()
376​
377 this.#currentRefetchInterval = nextInterval
378​
379 if (
380 isServer ||
381 this.options.enabled === false ||
382 !isValidTimeout(this.#currentRefetchInterval) ||
383 this.#currentRefetchInterval === 0
384 ) {
385 return
386 }
387​
388 this.#refetchIntervalId = setInterval(() => {
389 if (
390 this.options.refetchIntervalInBackground ||
391 focusManager.isFocused()
392 ) {
393 this.#executeFetch()
394 }
395 }, this.#currentRefetchInterval)
396 }
397​
398 #updateTimers(): void {
399 this.#updateStaleTimeout()
400 this.#updateRefetchInterval(this.#computeRefetchInterval())
401 }
402​
403 #clearStaleTimeout(): void {
404 if (this.#staleTimeoutId) {
405 clearTimeout(this.#staleTimeoutId)
406 this.#staleTimeoutId = undefined
407 }
408 }
409​
410 #clearRefetchInterval(): void {
411 if (this.#refetchIntervalId) {
412 clearInterval(this.#refetchIntervalId)
413 this.#refetchIntervalId = undefined
414 }
415 }
416​
417 protected createResult(
418 query: Query<TQueryFnData, TError, TQueryData, TQueryKey>,
419 options: QueryObserverOptions<
420 TQueryFnData,
421 TError,
422 TData,
423 TQueryData,
424 TQueryKey
425 >,
426 ): QueryObserverResult<TData, TError> {
427 const prevQuery = this.#currentQuery
428 const prevOptions = this.options
429 const prevResult = this.#currentResult as
430 | QueryObserverResult<TData, TError>
431 | undefined
432 const prevResultState = this.#currentResultState
433 const prevResultOptions = this.#currentResultOptions
434 const queryChange = query !== prevQuery
435 const queryInitialState = queryChange
436 ? query.state
437 : this.#currentQueryInitialState
438​
439 const { state } = query
440 let newState = { ...state }
441 let isPlaceholderData = false
442 let data: TData | undefined
443​
444 // Optimistically set result in fetching state if needed
445 if (options._optimisticResults) {
446 const mounted = this.hasListeners()
447​
448 const fetchOnMount = !mounted && shouldFetchOnMount(query, options)
449​
450 const fetchOptionally =
451 mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions)
452​
453 if (fetchOnMount || fetchOptionally) {
454 newState = {
455 ...newState,
456 ...fetchState(state.data, query.options),
457 }
458 }
459 if (options._optimisticResults === 'isRestoring') {
460 newState.fetchStatus = 'idle'
461 }
462 }
463​
464 let { error, errorUpdatedAt, status } = newState
465​
466 // Select data if needed
467 if (options.select && newState.data !== undefined) {
468 // Memoize select result
469 if (
470 prevResult &&
471 newState.data === prevResultState?.data &&
472 options.select === this.#selectFn
473 ) {
474 data = this.#selectResult
475 } else {
476 try {
477 this.#selectFn = options.select
478 data = options.select(newState.data)
479 data = replaceData(prevResult?.data, data, options)
480 this.#selectResult = data
481 this.#selectError = null
482 } catch (selectError) {
483 this.#selectError = selectError as TError
484 }
485 }
486 }
487 // Use query data
488 else {
489 data = newState.data as unknown as TData
490 }
491​
492 // Show placeholder data if needed
493 if (
494 options.placeholderData !== undefined &&
495 data === undefined &&
496 status === 'pending'
497 ) {
498 let placeholderData
499​
500 // Memoize placeholder data
501 if (
502 prevResult?.isPlaceholderData &&
503 options.placeholderData === prevResultOptions?.placeholderData
504 ) {
505 placeholderData = prevResult.data
506 } else {
507 placeholderData =
508 typeof options.placeholderData === 'function'
509 ? (
510 options.placeholderData as unknown as PlaceholderDataFunction<TQueryData>
511 )(
512 this.#lastQueryWithDefinedData?.state.data,
513 this.#lastQueryWithDefinedData as any,
514 )
515 : options.placeholderData
516 if (options.select && placeholderData !== undefined) {
517 try {
518 placeholderData = options.select(placeholderData)
519 this.#selectError = null
520 } catch (selectError) {
521 this.#selectError = selectError as TError
522 }
523 }
524 }
525​
526 if (placeholderData !== undefined) {
527 status = 'success'
528 data = replaceData(
529 prevResult?.data,
530 placeholderData as unknown,
531 options,
532 ) 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 = newState.fetchStatus === 'fetching'
545 const isPending = status === 'pending'
546 const isError = status === 'error'
547​
548 const isLoading = isPending && isFetching
549 const hasData = data !== undefined
550​
551 const result: QueryObserverBaseResult<TData, TError> = {
552 status,
553 fetchStatus: newState.fetchStatus,
554 isPending,
555 isSuccess: status === 'success',
556 isError,
557 isInitialLoading: isLoading,
558 isLoading,
559 data,
560 dataUpdatedAt: newState.dataUpdatedAt,
561 error,
562 errorUpdatedAt,
563 failureCount: newState.fetchFailureCount,
564 failureReason: newState.fetchFailureReason,
565 errorUpdateCount: newState.errorUpdateCount,
566 isFetched: newState.dataUpdateCount > 0 || newState.errorUpdateCount > 0,
567 isFetchedAfterMount:
568 newState.dataUpdateCount > queryInitialState.dataUpdateCount ||
569 newState.errorUpdateCount > queryInitialState.errorUpdateCount,
570 isFetching,
571 isRefetching: isFetching && !isPending,
572 isLoadingError: isError && !hasData,
573 isPaused: newState.fetchStatus === 'paused',
574 isPlaceholderData,
575 isRefetchError: isError && hasData,
576 isStale: isStale(query, options),
577 refetch: this.refetch,
578 }
579​
580 return result as QueryObserverResult<TData, TError>
581 }
582​
583 updateResult(notifyOptions?: NotifyOptions): void {
584 const prevResult = this.#currentResult as
585 | QueryObserverResult<TData, TError>
586 | undefined
587​
588 const nextResult = this.createResult(this.#currentQuery, this.options)
589 this.#currentResultState = this.#currentQuery.state
590 this.#currentResultOptions = this.options
591​
592 if (this.#currentResultState.data !== undefined) {
593 this.#lastQueryWithDefinedData = this.#currentQuery
594 }
595​
596 // Only notify and update result if something has changed
597 if (shallowEqualObjects(nextResult, prevResult)) {
598 return
599 }
600​
601 this.#currentResult = nextResult
602​
603 // Determine which callbacks to trigger
604 const defaultNotifyOptions: NotifyOptions = {}
605​
606 const shouldNotifyListeners = (): boolean => {
607 if (!prevResult) {
608 return true
609 }
610​
611 const { notifyOnChangeProps } = this.options
612 const notifyOnChangePropsValue =
613 typeof notifyOnChangeProps === 'function'
614 ? notifyOnChangeProps()
615 : notifyOnChangeProps
616​
617 if (
618 notifyOnChangePropsValue === 'all' ||
619 (!notifyOnChangePropsValue && !this.#trackedProps.size)
620 ) {
621 return true
622 }
623​
624 const includedProps = new Set(
625 notifyOnChangePropsValue ?? this.#trackedProps,
626 )
627​
628 if (this.options.throwOnError) {
629 includedProps.add('error')
630 }
631​
632 return Object.keys(this.#currentResult).some((key) => {
633 const typedKey = key as keyof QueryObserverResult
634 const changed = this.#currentResult[typedKey] !== prevResult[typedKey]
635 return changed && includedProps.has(typedKey)
636 })
637 }
638​
639 if (notifyOptions?.listeners !== false && shouldNotifyListeners()) {
640 defaultNotifyOptions.listeners = true
641 }
642​
643 this.#notify({ ...defaultNotifyOptions, ...notifyOptions })
644 }
645​
646 #updateQuery(): void {
647 const query = this.#client.getQueryCache().build(this.#client, this.options)
648​
649 if (query === this.#currentQuery) {
650 return
651 }
652​
653 const prevQuery = this.#currentQuery as
654 | Query<TQueryFnData, TError, TQueryData, TQueryKey>
655 | undefined
656 this.#currentQuery = query
657 this.#currentQueryInitialState = query.state
658​
659 if (this.hasListeners()) {
660 prevQuery?.removeObserver(this)
661 query.addObserver(this)
662 }
663 }
664​
665 onQueryUpdate(): void {
666 this.updateResult()
667​
668 if (this.hasListeners()) {
669 this.#updateTimers()
670 }
671 }
672​
673 #notify(notifyOptions: NotifyOptions): void {
674 notifyManager.batch(() => {
675 // First, trigger the listeners
676 if (notifyOptions.listeners) {
677 this.listeners.forEach((listener) => {
678 listener(this.#currentResult)
679 })
680 }
681​
682 // Then the cache listeners
683 this.#client.getQueryCache().notify({
684 query: this.#currentQuery,
685 type: 'observerResultsUpdated',
686 })
687 })
688 }
690​
691function shouldLoadOnMount(
692 query: Query<any, any, any, any>,
693 options: QueryObserverOptions<any, any, any, any>,
694): boolean {
695 return (
696 options.enabled !== false &&
697 query.state.data === undefined &&
698 !(query.state.status === 'error' && options.retryOnMount === false)
699 )
701​
702function shouldFetchOnMount(
703 query: Query<any, any, any, any>,
704 options: QueryObserverOptions<any, any, any, any, any>,
705): boolean {
706 return (
707 shouldLoadOnMount(query, options) ||
708 (query.state.data !== undefined &&
709 shouldFetchOn(query, options, options.refetchOnMount))
710 )
712​
713function shouldFetchOn(
714 query: Query<any, any, any, any>,
715 options: QueryObserverOptions<any, any, any, any, any>,
716 field: (typeof options)['refetchOnMount'] &
717 (typeof options)['refetchOnWindowFocus'] &
718 (typeof options)['refetchOnReconnect'],
719) {
720 if (options.enabled !== false) {
721 const value = typeof field === 'function' ? field(query) : field
722​
723 return value === 'always' || (value !== false && isStale(query, options))
724 }
725 return false
727​
728function shouldFetchOptionally(
729 query: Query<any, any, any, any>,
730 prevQuery: Query<any, any, any, any>,
731 options: QueryObserverOptions<any, any, any, any, any>,
732 prevOptions: QueryObserverOptions<any, any, any, any, any>,
733): boolean {
734 return (
735 (query !== prevQuery || prevOptions.enabled === false) &&
736 (!options.suspense || query.state.status !== 'error') &&
737 isStale(query, options)
738 )
740​
741function isStale(
742 query: Query<any, any, any, any>,
743 options: QueryObserverOptions<any, any, any, any, any>,
744): boolean {
745 return options.enabled !== false && query.isStaleByTime(options.staleTime)
747​
748// this function would decide if we will update the observer's 'current'
749// properties after an optimistic reading via getOptimisticResult
750function shouldAssignObserverCurrentProperties<
751 TQueryFnData = unknown,
752 TError = unknown,
753 TData = TQueryFnData,
754 TQueryData = TQueryFnData,
755 TQueryKey extends QueryKey = QueryKey,
756>(
757 observer: QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>,
758 optimisticResult: QueryObserverResult<TData, TError>,
759) {
760 // if the newly created result isn't what the observer is holding as current,
761 // then we'll need to update the properties as well
762 if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) {
763 return true
764 }
765​
766 // basically, just keep previous properties if nothing changed
767 return false