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

queryObserver.ts

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