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

queryObserver.ts

721 lines18.7 KB

1import type {
2 DefaultedQueryObserverOptions,
3 DefaultError,
4 PlaceholderDataFunction,
5 QueryKey,
6 QueryObserverBaseResult,
7 QueryObserverOptions,
8 QueryObserverResult,
9 QueryOptions,
10 RefetchOptions,
11} from './types'
12import {
13 isServer,
14 isValidTimeout,
15 noop,
16 replaceData,
17 shallowEqualObjects,
18 timeUntilStale,
19} from './utils'
20import { notifyManager } from './notifyManager'
21import type { Query, QueryState, FetchOptions } from './query'
22import type { QueryClient } from './queryClient'
23import { focusManager } from './focusManager'
24import { Subscribable } from './subscribable'
25import { canFetch } from './retryer'
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 return this.createResult(query, options)
231 }
232​
233 getCurrentResult(): QueryObserverResult<TData, TError> {
234 return this.#currentResult
235 }
236​
237 trackResult(
238 result: QueryObserverResult<TData, TError>,
239 ): QueryObserverResult<TData, TError> {
240 const trackedResult = {} as QueryObserverResult<TData, TError>
241​
242 Object.keys(result).forEach((key) => {
243 Object.defineProperty(trackedResult, key, {
244 configurable: false,
245 enumerable: true,
246 get: () => {
247 this.#trackedProps.add(key as keyof QueryObserverResult)
248 return result[key as keyof QueryObserverResult]
249 },
250 })
251 })
252​
253 return trackedResult
254 }
255​
256 getCurrentQuery(): Query<TQueryFnData, TError, TQueryData, TQueryKey> {
257 return this.#currentQuery
258 }
259​
260 refetch({ ...options }: RefetchOptions = {}): Promise<
261 QueryObserverResult<TData, TError>
262 > {
263 return this.fetch({
264 ...options,
265 })
266 }
267​
268 fetchOptimistic(
269 options: QueryObserverOptions<
270 TQueryFnData,
271 TError,
272 TData,
273 TQueryData,
274 TQueryKey
275 >,
276 ): Promise<QueryObserverResult<TData, TError>> {
277 const defaultedOptions = this.#client.defaultQueryOptions(options)
278​
279 const query = this.#client
280 .getQueryCache()
281 .build(this.#client, defaultedOptions)
282 query.isFetchingOptimistic = true
283​
284 return query.fetch().then(() => this.createResult(query, defaultedOptions))
285 }
286​
287 protected fetch(
288 fetchOptions: ObserverFetchOptions,
289 ): Promise<QueryObserverResult<TData, TError>> {
290 return this.#executeFetch({
291 ...fetchOptions,
292 cancelRefetch: fetchOptions.cancelRefetch ?? true,
293 }).then(() => {
294 this.#updateResult()
295 return this.#currentResult
296 })
297 }
298​
299 #executeFetch(
300 fetchOptions?: ObserverFetchOptions,
301 ): Promise<TQueryData | undefined> {
302 // Make sure we reference the latest query as the current one might have been removed
303 this.#updateQuery()
304​
305 // Fetch
306 let promise: Promise<TQueryData | undefined> = this.#currentQuery.fetch(
307 this.options as QueryOptions<TQueryFnData, TError, TQueryData, TQueryKey>,
308 fetchOptions,
309 )
310​
311 if (!fetchOptions?.throwOnError) {
312 promise = promise.catch(noop)
313 }
314​
315 return promise
316 }
317​
318 #updateStaleTimeout(): void {
319 this.#clearStaleTimeout()
320​
321 if (
322 isServer ||
323 this.#currentResult.isStale ||
324 !isValidTimeout(this.options.staleTime)
325 ) {
326 return
327 }
328​
329 const time = timeUntilStale(
330 this.#currentResult.dataUpdatedAt,
331 this.options.staleTime,
332 )
333​
334 // The timeout is sometimes triggered 1 ms before the stale time expiration.
335 // To mitigate this issue we always add 1 ms to the timeout.
336 const timeout = time + 1
337​
338 this.#staleTimeoutId = setTimeout(() => {
339 if (!this.#currentResult.isStale) {
340 this.#updateResult()
341 }
342 }, timeout)
343 }
344​
345 #computeRefetchInterval() {
346 return (
347 (typeof this.options.refetchInterval === 'function'
348 ? this.options.refetchInterval(
349 this.#currentResult.data,
350 this.#currentQuery,
351 )
352 : this.options.refetchInterval) ?? false
353 )
354 }
355​
356 #updateRefetchInterval(nextInterval: number | false): void {
357 this.#clearRefetchInterval()
358​
359 this.#currentRefetchInterval = nextInterval
360​
361 if (
362 isServer ||
363 this.options.enabled === false ||
364 !isValidTimeout(this.#currentRefetchInterval) ||
365 this.#currentRefetchInterval === 0
366 ) {
367 return
368 }
369​
370 this.#refetchIntervalId = setInterval(() => {
371 if (
372 this.options.refetchIntervalInBackground ||
373 focusManager.isFocused()
374 ) {
375 this.#executeFetch()
376 }
377 }, this.#currentRefetchInterval)
378 }
379​
380 #updateTimers(): void {
381 this.#updateStaleTimeout()
382 this.#updateRefetchInterval(this.#computeRefetchInterval())
383 }
384​
385 #clearStaleTimeout(): void {
386 if (this.#staleTimeoutId) {
387 clearTimeout(this.#staleTimeoutId)
388 this.#staleTimeoutId = undefined
389 }
390 }
391​
392 #clearRefetchInterval(): void {
393 if (this.#refetchIntervalId) {
394 clearInterval(this.#refetchIntervalId)
395 this.#refetchIntervalId = undefined
396 }
397 }
398​
399 protected createResult(
400 query: Query<TQueryFnData, TError, TQueryData, TQueryKey>,
401 options: QueryObserverOptions<
402 TQueryFnData,
403 TError,
404 TData,
405 TQueryData,
406 TQueryKey
407 >,
408 ): QueryObserverResult<TData, TError> {
409 const prevQuery = this.#currentQuery
410 const prevOptions = this.options
411 const prevResult = this.#currentResult as
412 | QueryObserverResult<TData, TError>
413 | undefined
414 const prevResultState = this.#currentResultState
415 const prevResultOptions = this.#currentResultOptions
416 const queryChange = query !== prevQuery
417 const queryInitialState = queryChange
418 ? query.state
419 : this.#currentQueryInitialState
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 )(
494 this.#lastQueryWithDefinedData?.state.data,
495 this.#lastQueryWithDefinedData as any,
496 )
497 : options.placeholderData
498 if (options.select && typeof placeholderData !== 'undefined') {
499 try {
500 placeholderData = options.select(placeholderData)
501 this.#selectError = null
502 } catch (selectError) {
503 this.#selectError = selectError as TError
504 }
505 }
506 }
507​
508 if (typeof placeholderData !== 'undefined') {
509 status = 'success'
510 data = replaceData(
511 prevResult?.data,
512 placeholderData as unknown,
513 options,
514 ) as TData
515 isPlaceholderData = true
516 }
517 }
518​
519 if (this.#selectError) {
520 error = this.#selectError as any
521 data = this.#selectResult
522 errorUpdatedAt = Date.now()
523 status = 'error'
524 }
525​
526 const isFetching = fetchStatus === 'fetching'
527 const isPending = status === 'pending'
528 const isError = status === 'error'
529​
530 const isLoading = isPending && isFetching
531​
532 const result: QueryObserverBaseResult<TData, TError> = {
533 status,
534 fetchStatus,
535 isPending,
536 isSuccess: status === 'success',
537 isError,
538 isInitialLoading: isLoading,
539 isLoading,
540 data,
541 dataUpdatedAt: state.dataUpdatedAt,
542 error,
543 errorUpdatedAt,
544 failureCount: state.fetchFailureCount,
545 failureReason: state.fetchFailureReason,
546 errorUpdateCount: state.errorUpdateCount,
547 isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
548 isFetchedAfterMount:
549 state.dataUpdateCount > queryInitialState.dataUpdateCount ||
550 state.errorUpdateCount > queryInitialState.errorUpdateCount,
551 isFetching,
552 isRefetching: isFetching && !isPending,
553 isLoadingError: isError && state.dataUpdatedAt === 0,
554 isPaused: fetchStatus === 'paused',
555 isPlaceholderData,
556 isRefetchError: isError && state.dataUpdatedAt !== 0,
557 isStale: isStale(query, options),
558 refetch: this.refetch,
559 }
560​
561 return result as QueryObserverResult<TData, TError>
562 }
563​
564 #updateResult(notifyOptions?: NotifyOptions): void {
565 const prevResult = this.#currentResult as
566 | QueryObserverResult<TData, TError>
567 | undefined
568​
569 const nextResult = this.createResult(this.#currentQuery, this.options)
570 this.#currentResultState = this.#currentQuery.state
571 this.#currentResultOptions = this.options
572​
573 // Only notify and update result if something has changed
574 if (shallowEqualObjects(nextResult, prevResult)) {
575 return
576 }
577​
578 if (this.#currentResultState.data !== undefined) {
579 this.#lastQueryWithDefinedData = this.#currentQuery
580 }
581 this.#currentResult = nextResult
582​
583 // Determine which callbacks to trigger
584 const defaultNotifyOptions: NotifyOptions = {}
585​
586 const shouldNotifyListeners = (): boolean => {
587 if (!prevResult) {
588 return true
589 }
590​
591 const { notifyOnChangeProps } = this.options
592​
593 if (
594 notifyOnChangeProps === 'all' ||
595 (!notifyOnChangeProps && !this.#trackedProps.size)
596 ) {
597 return true
598 }
599​
600 const includedProps = new Set(notifyOnChangeProps ?? this.#trackedProps)
601​
602 if (this.options.throwOnError) {
603 includedProps.add('error')
604 }
605​
606 return Object.keys(this.#currentResult).some((key) => {
607 const typedKey = key as keyof QueryObserverResult
608 const changed = this.#currentResult[typedKey] !== prevResult[typedKey]
609 return changed && includedProps.has(typedKey)
610 })
611 }
612​
613 if (notifyOptions?.listeners !== false && shouldNotifyListeners()) {
614 defaultNotifyOptions.listeners = true
615 }
616​
617 this.#notify({ ...defaultNotifyOptions, ...notifyOptions })
618 }
619​
620 #updateQuery(): void {
621 const query = this.#client.getQueryCache().build(this.#client, this.options)
622​
623 if (query === this.#currentQuery) {
624 return
625 }
626​
627 const prevQuery = this.#currentQuery as
628 | Query<TQueryFnData, TError, TQueryData, TQueryKey>
629 | undefined
630 this.#currentQuery = query
631 this.#currentQueryInitialState = query.state
632​
633 if (this.hasListeners()) {
634 prevQuery?.removeObserver(this)
635 query.addObserver(this)
636 }
637 }
638​
639 onQueryUpdate(): void {
640 this.#updateResult()
641​
642 if (this.hasListeners()) {
643 this.#updateTimers()
644 }
645 }
646​
647 #notify(notifyOptions: NotifyOptions): void {
648 notifyManager.batch(() => {
649 // First, trigger the listeners
650 if (notifyOptions.listeners) {
651 this.listeners.forEach((listener) => {
652 listener(this.#currentResult)
653 })
654 }
655​
656 // Then the cache listeners
657 this.#client.getQueryCache().notify({
658 query: this.#currentQuery,
659 type: 'observerResultsUpdated',
660 })
661 })
662 }
664​
665function shouldLoadOnMount(
666 query: Query<any, any, any, any>,
667 options: QueryObserverOptions<any, any, any, any>,
668): boolean {
669 return (
670 options.enabled !== false &&
671 !query.state.dataUpdatedAt &&
672 !(query.state.status === 'error' && options.retryOnMount === false)
673 )
675​
676function shouldFetchOnMount(
677 query: Query<any, any, any, any>,
678 options: QueryObserverOptions<any, any, any, any, any>,
679): boolean {
680 return (
681 shouldLoadOnMount(query, options) ||
682 (query.state.dataUpdatedAt > 0 &&
683 shouldFetchOn(query, options, options.refetchOnMount))
684 )
686​
687function shouldFetchOn(
688 query: Query<any, any, any, any>,
689 options: QueryObserverOptions<any, any, any, any, any>,
690 field: (typeof options)['refetchOnMount'] &
691 (typeof options)['refetchOnWindowFocus'] &
692 (typeof options)['refetchOnReconnect'],
693) {
694 if (options.enabled !== false) {
695 const value = typeof field === 'function' ? field(query) : field
696​
697 return value === 'always' || (value !== false && isStale(query, options))
698 }
699 return false
701​
702function shouldFetchOptionally(
703 query: Query<any, any, any, any>,
704 prevQuery: Query<any, any, any, any>,
705 options: QueryObserverOptions<any, any, any, any, any>,
706 prevOptions: QueryObserverOptions<any, any, any, any, any>,
707): boolean {
708 return (
709 options.enabled !== false &&
710 (query !== prevQuery || prevOptions.enabled === false) &&
711 (!options.suspense || query.state.status !== 'error') &&
712 isStale(query, options)
713 )
715​
716function isStale(
717 query: Query<any, any, any, any>,
718 options: QueryObserverOptions<any, any, any, any, any>,
719): boolean {
720 return query.isStaleByTime(options.staleTime)