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

queryObserver.ts

729 lines19.2 KB

1import type { DefaultedQueryObserverOptions, RegisteredError } from './types'
2import {
3 isServer,
4 isValidTimeout,
5 noop,
6 replaceData,
7 shallowEqualObjects,
8 timeUntilStale,
9} from './utils'
10import { notifyManager } from './notifyManager'
11import type {
12 PlaceholderDataFunction,
13 QueryKey,
14 QueryObserverBaseResult,
15 QueryObserverOptions,
16 QueryObserverResult,
17 QueryOptions,
18 RefetchOptions,
19} from './types'
20import type { Query, QueryState, Action, FetchOptions } from './query'
21import type { QueryClient } from './queryClient'
22import { focusManager } from './focusManager'
23import { Subscribable } from './subscribable'
24import { canFetch, isCancelledError } from './retryer'
25​
26type QueryObserverListener<TData, TError> = (
27 result: QueryObserverResult<TData, TError>,
28) => void
29​
30export interface NotifyOptions {
31 listeners?: boolean
32 onError?: boolean
33 onSuccess?: boolean
35​
36export interface ObserverFetchOptions extends FetchOptions {
37 throwOnError?: boolean
39​
40export class QueryObserver<
41 TQueryFnData = unknown,
42 TError = RegisteredError,
43 TData = TQueryFnData,
44 TQueryData = TQueryFnData,
45 TQueryKey extends QueryKey = QueryKey,
46> extends Subscribable<QueryObserverListener<TData, TError>> {
47 options: QueryObserverOptions<
48 TQueryFnData,
49 TError,
50 TData,
51 TQueryData,
52 TQueryKey
53 >
54​
55 #client: QueryClient
56 #currentQuery: Query<TQueryFnData, TError, TQueryData, TQueryKey> = undefined!
57 #currentQueryInitialState: QueryState<TQueryData, TError> = undefined!
58 #currentResult: QueryObserverResult<TData, TError> = undefined!
59 #currentResultState?: QueryState<TQueryData, TError>
60 #currentResultOptions?: QueryObserverOptions<
61 TQueryFnData,
62 TError,
63 TData,
64 TQueryData,
65 TQueryKey
66 >
67 #previousQueryResult?: QueryObserverResult<TData, TError>
68 #selectError: TError | null
69 #selectFn?: (data: TQueryData) => TData
70 #selectResult?: TData
71 #staleTimeoutId?: ReturnType<typeof setTimeout>
72 #refetchIntervalId?: ReturnType<typeof setInterval>
73 #currentRefetchInterval?: number | false
74 #trackedProps: Set<keyof QueryObserverResult> = new Set()
75​
76 constructor(
77 client: QueryClient,
78 options: QueryObserverOptions<
79 TQueryFnData,
80 TError,
81 TData,
82 TQueryData,
83 TQueryKey
84 >,
85 ) {
86 super()
87​
88 this.#client = client
89 this.options = options
90 this.#selectError = null
91 this.bindMethods()
92 this.setOptions(options)
93 }
94​
95 protected bindMethods(): void {
96 this.refetch = this.refetch.bind(this)
97 }
98​
99 protected onSubscribe(): void {
100 if (this.listeners.length === 1) {
101 this.#currentQuery.addObserver(this)
102​
103 if (shouldFetchOnMount(this.#currentQuery, this.options)) {
104 this.#executeFetch()
105 }
106​
107 this.#updateTimers()
108 }
109 }
110​
111 protected onUnsubscribe(): void {
112 if (!this.listeners.length) {
113 this.destroy()
114 }
115 }
116​
117 shouldFetchOnReconnect(): boolean {
118 return shouldFetchOn(
119 this.#currentQuery,
120 this.options,
121 this.options.refetchOnReconnect,
122 )
123 }
124​
125 shouldFetchOnWindowFocus(): boolean {
126 return shouldFetchOn(
127 this.#currentQuery,
128 this.options,
129 this.options.refetchOnWindowFocus,
130 )
131 }
132​
133 destroy(): void {
134 this.listeners = []
135 this.#clearStaleTimeout()
136 this.#clearRefetchInterval()
137 this.#currentQuery.removeObserver(this)
138 }
139​
140 setOptions(
141 options?: QueryObserverOptions<
142 TQueryFnData,
143 TError,
144 TData,
145 TQueryData,
146 TQueryKey
147 >,
148 notifyOptions?: NotifyOptions,
149 ): void {
150 const prevOptions = this.options
151 const prevQuery = this.#currentQuery
152​
153 this.options = this.#client.defaultQueryOptions(options)
154​
155 if (!shallowEqualObjects(prevOptions, this.options)) {
156 this.#client.getQueryCache().notify({
157 type: 'observerOptionsUpdated',
158 query: this.#currentQuery,
159 observer: this,
160 })
161 }
162​
163 if (
164 typeof this.options.enabled !== 'undefined' &&
165 typeof this.options.enabled !== 'boolean'
166 ) {
167 throw new Error('Expected enabled to be a boolean')
168 }
169​
170 // Keep previous query key if the user does not supply one
171 if (!this.options.queryKey) {
172 this.options.queryKey = prevOptions.queryKey
173 }
174​
175 this.#updateQuery()
176​
177 const mounted = this.hasListeners()
178​
179 // Fetch if there are subscribers
180 if (
181 mounted &&
182 shouldFetchOptionally(
183 this.#currentQuery,
184 prevQuery,
185 this.options,
186 prevOptions,
187 )
188 ) {
189 this.#executeFetch()
190 }
191​
192 // Update result
193 this.#updateResult(notifyOptions)
194​
195 // Update stale interval if needed
196 if (
197 mounted &&
198 (this.#currentQuery !== prevQuery ||
199 this.options.enabled !== prevOptions.enabled ||
200 this.options.staleTime !== prevOptions.staleTime)
201 ) {
202 this.#updateStaleTimeout()
203 }
204​
205 const nextRefetchInterval = this.#computeRefetchInterval()
206​
207 // Update refetch interval if needed
208 if (
209 mounted &&
210 (this.#currentQuery !== prevQuery ||
211 this.options.enabled !== prevOptions.enabled ||
212 nextRefetchInterval !== this.#currentRefetchInterval)
213 ) {
214 this.#updateRefetchInterval(nextRefetchInterval)
215 }
216 }
217​
218 getOptimisticResult(
219 options: DefaultedQueryObserverOptions<
220 TQueryFnData,
221 TError,
222 TData,
223 TQueryData,
224 TQueryKey
225 >,
226 ): QueryObserverResult<TData, TError> {
227 const query = this.#client.getQueryCache().build(this.#client, options)
228​
229 return this.createResult(query, options)
230 }
231​
232 getCurrentResult(): QueryObserverResult<TData, TError> {
233 return this.#currentResult
234 }
235​
236 trackResult(
237 result: QueryObserverResult<TData, TError>,
238 ): QueryObserverResult<TData, TError> {
239 const trackedResult = {} as QueryObserverResult<TData, TError>
240​
241 Object.keys(result).forEach((key) => {
242 Object.defineProperty(trackedResult, key, {
243 configurable: false,
244 enumerable: true,
245 get: () => {
246 this.#trackedProps.add(key as keyof QueryObserverResult)
247 return result[key as keyof QueryObserverResult]
248 },
249 })
250 })
251​
252 return trackedResult
253 }
254​
255 getCurrentQuery(): Query<TQueryFnData, TError, TQueryData, TQueryKey> {
256 return this.#currentQuery
257 }
258​
259 refetch({ ...options }: RefetchOptions = {}): Promise<
260 QueryObserverResult<TData, TError>
261 > {
262 return this.fetch({
263 ...options,
264 })
265 }
266​
267 fetchOptimistic(
268 options: QueryObserverOptions<
269 TQueryFnData,
270 TError,
271 TData,
272 TQueryData,
273 TQueryKey
274 >,
275 ): Promise<QueryObserverResult<TData, TError>> {
276 const defaultedOptions = this.#client.defaultQueryOptions(options)
277​
278 const query = this.#client
279 .getQueryCache()
280 .build(this.#client, defaultedOptions)
281 query.isFetchingOptimistic = true
282​
283 return query.fetch().then(() => this.createResult(query, defaultedOptions))
284 }
285​
286 protected fetch(
287 fetchOptions: ObserverFetchOptions,
288 ): Promise<QueryObserverResult<TData, TError>> {
289 return this.#executeFetch({
290 ...fetchOptions,
291 cancelRefetch: fetchOptions.cancelRefetch ?? true,
292 }).then(() => {
293 this.#updateResult()
294 return this.#currentResult
295 })
296 }
297​
298 #executeFetch(
299 fetchOptions?: ObserverFetchOptions,
300 ): Promise<TQueryData | undefined> {
301 // Make sure we reference the latest query as the current one might have been removed
302 this.#updateQuery()
303​
304 // Fetch
305 let promise: Promise<TQueryData | undefined> = this.#currentQuery.fetch(
306 this.options as QueryOptions<TQueryFnData, TError, TQueryData, TQueryKey>,
307 fetchOptions,
308 )
309​
310 if (!fetchOptions?.throwOnError) {
311 promise = promise.catch(noop)
312 }
313​
314 return promise
315 }
316​
317 #updateStaleTimeout(): void {
318 this.#clearStaleTimeout()
319​
320 if (
321 isServer ||
322 this.#currentResult.isStale ||
323 !isValidTimeout(this.options.staleTime)
324 ) {
325 return
326 }
327​
328 const time = timeUntilStale(
329 this.#currentResult.dataUpdatedAt,
330 this.options.staleTime,
331 )
332​
333 // The timeout is sometimes triggered 1 ms before the stale time expiration.
334 // To mitigate this issue we always add 1 ms to the timeout.
335 const timeout = time + 1
336​
337 this.#staleTimeoutId = setTimeout(() => {
338 if (!this.#currentResult.isStale) {
339 this.#updateResult()
340 }
341 }, timeout)
342 }
343​
344 #computeRefetchInterval() {
345 return typeof this.options.refetchInterval === 'function'
346 ? this.options.refetchInterval(
347 this.#currentResult.data,
348 this.#currentQuery,
349 )
350 : this.options.refetchInterval ?? false
351 }
352​
353 #updateRefetchInterval(nextInterval: number | false): void {
354 this.#clearRefetchInterval()
355​
356 this.#currentRefetchInterval = nextInterval
357​
358 if (
359 isServer ||
360 this.options.enabled === false ||
361 !isValidTimeout(this.#currentRefetchInterval) ||
362 this.#currentRefetchInterval === 0
363 ) {
364 return
365 }
366​
367 this.#refetchIntervalId = setInterval(() => {
368 if (
369 this.options.refetchIntervalInBackground ||
370 focusManager.isFocused()
371 ) {
372 this.#executeFetch()
373 }
374 }, this.#currentRefetchInterval)
375 }
376​
377 #updateTimers(): void {
378 this.#updateStaleTimeout()
379 this.#updateRefetchInterval(this.#computeRefetchInterval())
380 }
381​
382 #clearStaleTimeout(): void {
383 if (this.#staleTimeoutId) {
384 clearTimeout(this.#staleTimeoutId)
385 this.#staleTimeoutId = undefined
386 }
387 }
388​
389 #clearRefetchInterval(): void {
390 if (this.#refetchIntervalId) {
391 clearInterval(this.#refetchIntervalId)
392 this.#refetchIntervalId = undefined
393 }
394 }
395​
396 protected createResult(
397 query: Query<TQueryFnData, TError, TQueryData, TQueryKey>,
398 options: QueryObserverOptions<
399 TQueryFnData,
400 TError,
401 TData,
402 TQueryData,
403 TQueryKey
404 >,
405 ): QueryObserverResult<TData, TError> {
406 const prevQuery = this.#currentQuery
407 const prevOptions = this.options
408 const prevResult = this.#currentResult as
409 | QueryObserverResult<TData, TError>
410 | undefined
411 const prevResultState = this.#currentResultState
412 const prevResultOptions = this.#currentResultOptions
413 const queryChange = query !== prevQuery
414 const queryInitialState = queryChange
415 ? query.state
416 : this.#currentQueryInitialState
417 const prevQueryResult = queryChange
418 ? this.#currentResult
419 : this.#previousQueryResult
420​
421 const { state } = query
422 let { error, errorUpdatedAt, fetchStatus, status } = state
423 let isPlaceholderData = false
424 let data: TData | undefined
425​
426 // Optimistically set result in fetching state if needed
427 if (options._optimisticResults) {
428 const mounted = this.hasListeners()
429​
430 const fetchOnMount = !mounted && shouldFetchOnMount(query, options)
431​
432 const fetchOptionally =
433 mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions)
434​
435 if (fetchOnMount || fetchOptionally) {
436 fetchStatus = canFetch(query.options.networkMode)
437 ? 'fetching'
438 : 'paused'
439 if (!state.dataUpdatedAt) {
440 status = 'pending'
441 }
442 }
443 if (options._optimisticResults === 'isRestoring') {
444 fetchStatus = 'idle'
445 }
446 }
447​
448 // Select data if needed
449 if (options.select && typeof state.data !== 'undefined') {
450 // Memoize select result
451 if (
452 prevResult &&
453 state.data === prevResultState?.data &&
454 options.select === this.#selectFn
455 ) {
456 data = this.#selectResult
457 } else {
458 try {
459 this.#selectFn = options.select
460 data = options.select(state.data)
461 data = replaceData(prevResult?.data, data, options)
462 this.#selectResult = data
463 this.#selectError = null
464 } catch (selectError) {
465 this.#selectError = selectError as TError
466 }
467 }
468 }
469 // Use query data
470 else {
471 data = state.data as unknown as TData
472 }
473​
474 // Show placeholder data if needed
475 if (
476 typeof options.placeholderData !== 'undefined' &&
477 typeof data === 'undefined' &&
478 status === 'pending'
479 ) {
480 let placeholderData
481​
482 // Memoize placeholder data
483 if (
484 prevResult?.isPlaceholderData &&
485 options.placeholderData === prevResultOptions?.placeholderData
486 ) {
487 placeholderData = prevResult.data
488 } else {
489 placeholderData =
490 typeof options.placeholderData === 'function'
491 ? (
492 options.placeholderData as unknown as PlaceholderDataFunction<TQueryData>
493 )(prevQueryResult?.data as TQueryData | undefined)
494 : options.placeholderData
495 if (options.select && typeof placeholderData !== 'undefined') {
496 try {
497 placeholderData = options.select(placeholderData)
498 this.#selectError = null
499 } catch (selectError) {
500 this.#selectError = selectError as TError
501 }
502 }
503 }
504​
505 if (typeof placeholderData !== 'undefined') {
506 status = 'success'
507 data = replaceData(prevResult?.data, placeholderData, options) as TData
508 isPlaceholderData = true
509 }
510 }
511​
512 if (this.#selectError) {
513 error = this.#selectError as any
514 data = this.#selectResult
515 errorUpdatedAt = Date.now()
516 status = 'error'
517 }
518​
519 const isFetching = fetchStatus === 'fetching'
520 const isPending = status === 'pending'
521 const isError = status === 'error'
522​
523 const isLoading = isPending && isFetching
524​
525 const result: QueryObserverBaseResult<TData, TError> = {
526 status,
527 fetchStatus,
528 isPending,
529 isSuccess: status === 'success',
530 isError,
531 isInitialLoading: isLoading,
532 isLoading,
533 data,
534 dataUpdatedAt: state.dataUpdatedAt,
535 error,
536 errorUpdatedAt,
537 failureCount: state.fetchFailureCount,
538 failureReason: state.fetchFailureReason,
539 errorUpdateCount: state.errorUpdateCount,
540 isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
541 isFetchedAfterMount:
542 state.dataUpdateCount > queryInitialState.dataUpdateCount ||
543 state.errorUpdateCount > queryInitialState.errorUpdateCount,
544 isFetching,
545 isRefetching: isFetching && !isPending,
546 isLoadingError: isError && state.dataUpdatedAt === 0,
547 isPaused: fetchStatus === 'paused',
548 isPlaceholderData,
549 isRefetchError: isError && state.dataUpdatedAt !== 0,
550 isStale: isStale(query, options),
551 refetch: this.refetch,
552 }
553​
554 return result as QueryObserverResult<TData, TError>
555 }
556​
557 #updateResult(notifyOptions?: NotifyOptions): void {
558 const prevResult = this.#currentResult as
559 | QueryObserverResult<TData, TError>
560 | undefined
561​
562 const nextResult = this.createResult(this.#currentQuery, this.options)
563 this.#currentResultState = this.#currentQuery.state
564 this.#currentResultOptions = this.options
565​
566 // Only notify and update result if something has changed
567 if (shallowEqualObjects(nextResult, prevResult)) {
568 return
569 }
570​
571 this.#currentResult = nextResult
572​
573 // Determine which callbacks to trigger
574 const defaultNotifyOptions: NotifyOptions = {}
575​
576 const shouldNotifyListeners = (): boolean => {
577 if (!prevResult) {
578 return true
579 }
580​
581 const { notifyOnChangeProps } = this.options
582​
583 if (
584 notifyOnChangeProps === 'all' ||
585 (!notifyOnChangeProps && !this.#trackedProps.size)
586 ) {
587 return true
588 }
589​
590 const includedProps = new Set(notifyOnChangeProps ?? this.#trackedProps)
591​
592 if (this.options.throwErrors) {
593 includedProps.add('error')
594 }
595​
596 return Object.keys(this.#currentResult).some((key) => {
597 const typedKey = key as keyof QueryObserverResult
598 const changed = this.#currentResult[typedKey] !== prevResult[typedKey]
599 return changed && includedProps.has(typedKey)
600 })
601 }
602​
603 if (notifyOptions?.listeners !== false && shouldNotifyListeners()) {
604 defaultNotifyOptions.listeners = true
605 }
606​
607 this.#notify({ ...defaultNotifyOptions, ...notifyOptions })
608 }
609​
610 #updateQuery(): void {
611 const query = this.#client.getQueryCache().build(this.#client, this.options)
612​
613 if (query === this.#currentQuery) {
614 return
615 }
616​
617 const prevQuery = this.#currentQuery as
618 | Query<TQueryFnData, TError, TQueryData, TQueryKey>
619 | undefined
620 this.#currentQuery = query
621 this.#currentQueryInitialState = query.state
622 this.#previousQueryResult = this.#currentResult
623​
624 if (this.hasListeners()) {
625 prevQuery?.removeObserver(this)
626 query.addObserver(this)
627 }
628 }
629​
630 onQueryUpdate(action: Action<TData, TError>): void {
631 const notifyOptions: NotifyOptions = {}
632​
633 if (action.type === 'success') {
634 notifyOptions.onSuccess = !action.manual
635 } else if (action.type === 'error' && !isCancelledError(action.error)) {
636 notifyOptions.onError = true
637 }
638​
639 this.#updateResult(notifyOptions)
640​
641 if (this.hasListeners()) {
642 this.#updateTimers()
643 }
644 }
645​
646 #notify(notifyOptions: NotifyOptions): void {
647 notifyManager.batch(() => {
648 // First trigger the configuration callbacks
649 if (notifyOptions.onSuccess) {
650 this.options.onSuccess?.(this.#currentResult.data!)
651 this.options.onSettled?.(this.#currentResult.data!, null)
652 } else if (notifyOptions.onError) {
653 this.options.onError?.(this.#currentResult.error!)
654 this.options.onSettled?.(undefined, this.#currentResult.error!)
655 }
656​
657 // Then trigger the listeners
658 if (notifyOptions.listeners) {
659 this.listeners.forEach((listener) => {
660 listener(this.#currentResult)
661 })
662 }
663​
664 // Then the cache listeners
665 this.#client.getQueryCache().notify({
666 query: this.#currentQuery,
667 type: 'observerResultsUpdated',
668 })
669 })
670 }
672​
673function shouldLoadOnMount(
674 query: Query<any, any, any, any>,
675 options: QueryObserverOptions<any, any, any, any>,
676): boolean {
677 return (
678 options.enabled !== false &&
679 !query.state.dataUpdatedAt &&
680 !(query.state.status === 'error' && options.retryOnMount === false)
681 )
683​
684function shouldFetchOnMount(
685 query: Query<any, any, any, any>,
686 options: QueryObserverOptions<any, any, any, any, any>,
687): boolean {
688 return (
689 shouldLoadOnMount(query, options) ||
690 (query.state.dataUpdatedAt > 0 &&
691 shouldFetchOn(query, options, options.refetchOnMount))
692 )
694​
695function shouldFetchOn(
696 query: Query<any, any, any, any>,
697 options: QueryObserverOptions<any, any, any, any, any>,
698 field: (typeof options)['refetchOnMount'] &
699 (typeof options)['refetchOnWindowFocus'] &
700 (typeof options)['refetchOnReconnect'],
701) {
702 if (options.enabled !== false) {
703 const value = typeof field === 'function' ? field(query) : field
704​
705 return value === 'always' || (value !== false && isStale(query, options))
706 }
707 return false
709​
710function shouldFetchOptionally(
711 query: Query<any, any, any, any>,
712 prevQuery: Query<any, any, any, any>,
713 options: QueryObserverOptions<any, any, any, any, any>,
714 prevOptions: QueryObserverOptions<any, any, any, any, any>,
715): boolean {
716 return (
717 options.enabled !== false &&
718 (query !== prevQuery || prevOptions.enabled === false) &&
719 (!options.suspense || query.state.status !== 'error') &&
720 isStale(query, options)
721 )
723​
724function isStale(
725 query: Query<any, any, any, any>,
726 options: QueryObserverOptions<any, any, any, any, any>,
727): boolean {
728 return query.isStaleByTime(options.staleTime)