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

queryObserver.ts

784 lines21.7 KB

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