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

queryObserver.ts

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