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

queryObserver.ts

772 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 { 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 } 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.#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 (!shallowEqualObjects(prevOptions, this.options)) {
159 this.#client.getQueryCache().notify({
160 type: 'observerOptionsUpdated',
161 query: this.#currentQuery,
162 observer: this,
163 })
164 }
165​
166 if (
167 typeof this.options.enabled !== 'undefined' &&
168 typeof this.options.enabled !== 'boolean'
169 ) {
170 throw new Error('Expected enabled to be a boolean')
171 }
172​
173 // Keep previous query key if the user does not supply one
174 if (!this.options.queryKey) {
175 this.options.queryKey = prevOptions.queryKey
176 }
177​
178 this.#updateQuery()
179​
180 const mounted = this.hasListeners()
181​
182 // Fetch if there are subscribers
183 if (
184 mounted &&
185 shouldFetchOptionally(
186 this.#currentQuery,
187 prevQuery,
188 this.options,
189 prevOptions,
190 )
191 ) {
192 this.#executeFetch()
193 }
194​
195 // Update result
196 this.updateResult(notifyOptions)
197​
198 // Update stale interval if needed
199 if (
200 mounted &&
201 (this.#currentQuery !== prevQuery ||
202 this.options.enabled !== prevOptions.enabled ||
203 this.options.staleTime !== prevOptions.staleTime)
204 ) {
205 this.#updateStaleTimeout()
206 }
207​
208 const nextRefetchInterval = this.#computeRefetchInterval()
209​
210 // Update refetch interval if needed
211 if (
212 mounted &&
213 (this.#currentQuery !== prevQuery ||
214 this.options.enabled !== prevOptions.enabled ||
215 nextRefetchInterval !== this.#currentRefetchInterval)
216 ) {
217 this.#updateRefetchInterval(nextRefetchInterval)
218 }
219 }
220​
221 getOptimisticResult(
222 options: DefaultedQueryObserverOptions<
223 TQueryFnData,
224 TError,
225 TData,
226 TQueryData,
227 TQueryKey
228 >,
229 ): QueryObserverResult<TData, TError> {
230 const query = this.#client.getQueryCache().build(this.#client, options)
231​
232 const result = this.createResult(query, options)
233​
234 if (shouldAssignObserverCurrentProperties(this, result)) {
235 // this assigns the optimistic result to the current Observer
236 // because if the query function changes, useQuery will be performing
237 // an effect where it would fetch again.
238 // When the fetch finishes, we perform a deep data cloning in order
239 // to reuse objects references. This deep data clone is performed against
240 // the `observer.currentResult.data` property
241 // When QueryKey changes, we refresh the query and get new `optimistic`
242 // result, while we leave the `observer.currentResult`, so when new data
243 // arrives, it finds the old `observer.currentResult` which is related
244 // to the old QueryKey. Which means that currentResult and selectData are
245 // out of sync already.
246 // To solve this, we move the cursor of the currentResult everytime
247 // an observer reads an optimistic value.
248​
249 // When keeping the previous data, the result doesn't change until new
250 // data arrives.
251 this.#currentResult = result
252 this.#currentResultOptions = this.options
253 this.#currentResultState = this.#currentQuery.state
254 }
255 return result
256 }
257​
258 getCurrentResult(): QueryObserverResult<TData, TError> {
259 return this.#currentResult
260 }
261​
262 trackResult(
263 result: QueryObserverResult<TData, TError>,
264 ): QueryObserverResult<TData, TError> {
265 const trackedResult = {} as QueryObserverResult<TData, TError>
266​
267 Object.keys(result).forEach((key) => {
268 Object.defineProperty(trackedResult, key, {
269 configurable: false,
270 enumerable: true,
271 get: () => {
272 this.#trackedProps.add(key as keyof QueryObserverResult)
273 return result[key as keyof QueryObserverResult]
274 },
275 })
276 })
277​
278 return trackedResult
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 query.isFetchingOptimistic = true
308​
309 return query.fetch().then(() => this.createResult(query, defaultedOptions))
310 }
311​
312 protected fetch(
313 fetchOptions: ObserverFetchOptions,
314 ): Promise<QueryObserverResult<TData, TError>> {
315 return this.#executeFetch({
316 ...fetchOptions,
317 cancelRefetch: fetchOptions.cancelRefetch ?? true,
318 }).then(() => {
319 this.updateResult()
320 return this.#currentResult
321 })
322 }
323​
324 #executeFetch(
325 fetchOptions?: ObserverFetchOptions,
326 ): Promise<TQueryData | undefined> {
327 // Make sure we reference the latest query as the current one might have been removed
328 this.#updateQuery()
329​
330 // Fetch
331 let promise: Promise<TQueryData | undefined> = this.#currentQuery.fetch(
332 this.options as QueryOptions<TQueryFnData, TError, TQueryData, TQueryKey>,
333 fetchOptions,
334 )
335​
336 if (!fetchOptions?.throwOnError) {
337 promise = promise.catch(noop)
338 }
339​
340 return promise
341 }
342​
343 #updateStaleTimeout(): void {
344 this.#clearStaleTimeout()
345​
346 if (
347 isServer ||
348 this.#currentResult.isStale ||
349 !isValidTimeout(this.options.staleTime)
350 ) {
351 return
352 }
353​
354 const time = timeUntilStale(
355 this.#currentResult.dataUpdatedAt,
356 this.options.staleTime,
357 )
358​
359 // The timeout is sometimes triggered 1 ms before the stale time expiration.
360 // To mitigate this issue we always add 1 ms to the timeout.
361 const timeout = time + 1
362​
363 this.#staleTimeoutId = setTimeout(() => {
364 if (!this.#currentResult.isStale) {
365 this.updateResult()
366 }
367 }, timeout)
368 }
369​
370 #computeRefetchInterval() {
371 return (
372 (typeof this.options.refetchInterval === 'function'
373 ? this.options.refetchInterval(this.#currentQuery)
374 : this.options.refetchInterval) ?? false
375 )
376 }
377​
378 #updateRefetchInterval(nextInterval: number | false): void {
379 this.#clearRefetchInterval()
380​
381 this.#currentRefetchInterval = nextInterval
382​
383 if (
384 isServer ||
385 this.options.enabled === false ||
386 !isValidTimeout(this.#currentRefetchInterval) ||
387 this.#currentRefetchInterval === 0
388 ) {
389 return
390 }
391​
392 this.#refetchIntervalId = setInterval(() => {
393 if (
394 this.options.refetchIntervalInBackground ||
395 focusManager.isFocused()
396 ) {
397 this.#executeFetch()
398 }
399 }, this.#currentRefetchInterval)
400 }
401​
402 #updateTimers(): void {
403 this.#updateStaleTimeout()
404 this.#updateRefetchInterval(this.#computeRefetchInterval())
405 }
406​
407 #clearStaleTimeout(): void {
408 if (this.#staleTimeoutId) {
409 clearTimeout(this.#staleTimeoutId)
410 this.#staleTimeoutId = undefined
411 }
412 }
413​
414 #clearRefetchInterval(): void {
415 if (this.#refetchIntervalId) {
416 clearInterval(this.#refetchIntervalId)
417 this.#refetchIntervalId = undefined
418 }
419 }
420​
421 protected createResult(
422 query: Query<TQueryFnData, TError, TQueryData, TQueryKey>,
423 options: QueryObserverOptions<
424 TQueryFnData,
425 TError,
426 TData,
427 TQueryData,
428 TQueryKey
429 >,
430 ): QueryObserverResult<TData, TError> {
431 const prevQuery = this.#currentQuery
432 const prevOptions = this.options
433 const prevResult = this.#currentResult as
434 | QueryObserverResult<TData, TError>
435 | undefined
436 const prevResultState = this.#currentResultState
437 const prevResultOptions = this.#currentResultOptions
438 const queryChange = query !== prevQuery
439 const queryInitialState = queryChange
440 ? query.state
441 : this.#currentQueryInitialState
442​
443 const { state } = query
444 let { error, errorUpdatedAt, fetchStatus, status } = state
445 let isPlaceholderData = false
446 let data: TData | undefined
447​
448 // Optimistically set result in fetching state if needed
449 if (options._optimisticResults) {
450 const mounted = this.hasListeners()
451​
452 const fetchOnMount = !mounted && shouldFetchOnMount(query, options)
453​
454 const fetchOptionally =
455 mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions)
456​
457 if (fetchOnMount || fetchOptionally) {
458 fetchStatus = canFetch(query.options.networkMode)
459 ? 'fetching'
460 : 'paused'
461 if (!state.dataUpdatedAt) {
462 status = 'pending'
463 }
464 }
465 if (options._optimisticResults === 'isRestoring') {
466 fetchStatus = 'idle'
467 }
468 }
469​
470 // Select data if needed
471 if (options.select && typeof state.data !== 'undefined') {
472 // Memoize select result
473 if (
474 prevResult &&
475 state.data === prevResultState?.data &&
476 options.select === this.#selectFn
477 ) {
478 data = this.#selectResult
479 } else {
480 try {
481 this.#selectFn = options.select
482 data = options.select(state.data)
483 data = replaceData(prevResult?.data, data, options)
484 this.#selectResult = data
485 this.#selectError = null
486 } catch (selectError) {
487 this.#selectError = selectError as TError
488 }
489 }
490 }
491 // Use query data
492 else {
493 data = state.data as unknown as TData
494 }
495​
496 // Show placeholder data if needed
497 if (
498 typeof options.placeholderData !== 'undefined' &&
499 typeof data === 'undefined' &&
500 status === 'pending'
501 ) {
502 let placeholderData
503​
504 // Memoize placeholder data
505 if (
506 prevResult?.isPlaceholderData &&
507 options.placeholderData === prevResultOptions?.placeholderData
508 ) {
509 placeholderData = prevResult.data
510 } else {
511 placeholderData =
512 typeof options.placeholderData === 'function'
513 ? (
514 options.placeholderData as unknown as PlaceholderDataFunction<TQueryData>
515 )(
516 this.#lastQueryWithDefinedData?.state.data,
517 this.#lastQueryWithDefinedData as any,
518 )
519 : options.placeholderData
520 if (options.select && typeof placeholderData !== 'undefined') {
521 try {
522 placeholderData = options.select(placeholderData)
523 this.#selectError = null
524 } catch (selectError) {
525 this.#selectError = selectError as TError
526 }
527 }
528 }
529​
530 if (typeof placeholderData !== 'undefined') {
531 status = 'success'
532 data = replaceData(
533 prevResult?.data,
534 placeholderData as unknown,
535 options,
536 ) as TData
537 isPlaceholderData = true
538 }
539 }
540​
541 if (this.#selectError) {
542 error = this.#selectError as any
543 data = this.#selectResult
544 errorUpdatedAt = Date.now()
545 status = 'error'
546 }
547​
548 const isFetching = fetchStatus === 'fetching'
549 const isPending = status === 'pending'
550 const isError = status === 'error'
551​
552 const isLoading = isPending && isFetching
553​
554 const result: QueryObserverBaseResult<TData, TError> = {
555 status,
556 fetchStatus,
557 isPending,
558 isSuccess: status === 'success',
559 isError,
560 isInitialLoading: isLoading,
561 isLoading,
562 data,
563 dataUpdatedAt: state.dataUpdatedAt,
564 error,
565 errorUpdatedAt,
566 failureCount: state.fetchFailureCount,
567 failureReason: state.fetchFailureReason,
568 errorUpdateCount: state.errorUpdateCount,
569 isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
570 isFetchedAfterMount:
571 state.dataUpdateCount > queryInitialState.dataUpdateCount ||
572 state.errorUpdateCount > queryInitialState.errorUpdateCount,
573 isFetching,
574 isRefetching: isFetching && !isPending,
575 isLoadingError: isError && state.dataUpdatedAt === 0,
576 isPaused: fetchStatus === 'paused',
577 isPlaceholderData,
578 isRefetchError: isError && state.dataUpdatedAt !== 0,
579 isStale: isStale(query, options),
580 refetch: this.refetch,
581 }
582​
583 return result as QueryObserverResult<TData, TError>
584 }
585​
586 updateResult(notifyOptions?: NotifyOptions): void {
587 const prevResult = this.#currentResult as
588 | QueryObserverResult<TData, TError>
589 | undefined
590​
591 const nextResult = this.createResult(this.#currentQuery, this.options)
592 this.#currentResultState = this.#currentQuery.state
593 this.#currentResultOptions = this.options
594​
595 if (this.#currentResultState.data !== undefined) {
596 this.#lastQueryWithDefinedData = this.#currentQuery
597 }
598​
599 // Only notify and update result if something has changed
600 if (shallowEqualObjects(nextResult, prevResult)) {
601 return
602 }
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