Open History to see the last commit
1import type { DefaultedQueryObserverOptions, DefaultError } 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, FetchOptions } from './query'
21import type { QueryClient } from './queryClient'
22import { focusManager } from './focusManager'
23import { Subscribable } from './subscribable'
24import { canFetch } from './retryer'
25β
26type QueryObserverListener<TData, TError> = (
27 result: QueryObserverResult<TData, TError>,
28) => void
29β
30export interface NotifyOptions {
31 listeners?: boolean
32}
33β
34export interface ObserverFetchOptions extends FetchOptions {
35 throwOnError?: boolean
36}
37β
38export class QueryObserver<
39 TQueryFnData = unknown,
40 TError = DefaultError,
41 TData = TQueryFnData,
42 TQueryData = TQueryFnData,
43 TQueryKey extends QueryKey = QueryKey,
44> extends Subscribable<QueryObserverListener<TData, TError>> {
45 options: QueryObserverOptions<
46 TQueryFnData,
47 TError,
48 TData,
49 TQueryData,
50 TQueryKey
51 >
52β
53 #client: QueryClient
54 #currentQuery: Query<TQueryFnData, TError, TQueryData, TQueryKey> = undefined!
55 #currentQueryInitialState: QueryState<TQueryData, TError> = undefined!
56 #currentResult: QueryObserverResult<TData, TError> = undefined!
57 #currentResultState?: QueryState<TQueryData, TError>
58 #currentResultOptions?: QueryObserverOptions<
59 TQueryFnData,
60 TError,
61 TData,
62 TQueryData,
63 TQueryKey
64 >
65 #selectError: TError | null
66 #selectFn?: (data: TQueryData) => TData
67 #selectResult?: TData
68 // This property keeps track of the last defined query data.
69 // It will be used to pass the previous data to the placeholder function between renders.
70 #lastDefinedQueryData?: TQueryData
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 (
346 (typeof this.options.refetchInterval === 'function'
347 ? this.options.refetchInterval(
348 this.#currentResult.data,
349 this.#currentQuery,
350 )
351 : this.options.refetchInterval) ?? false
352 )
353 }
354β
355 #updateRefetchInterval(nextInterval: number | false): void {
356 this.#clearRefetchInterval()
357β
358 this.#currentRefetchInterval = nextInterval
359β
360 if (
361 isServer ||
362 this.options.enabled === false ||
363 !isValidTimeout(this.#currentRefetchInterval) ||
364 this.#currentRefetchInterval === 0
365 ) {
366 return
367 }
368β
369 this.#refetchIntervalId = setInterval(() => {
370 if (
371 this.options.refetchIntervalInBackground ||
372 focusManager.isFocused()
373 ) {
374 this.#executeFetch()
375 }
376 }, this.#currentRefetchInterval)
377 }
378β
379 #updateTimers(): void {
380 this.#updateStaleTimeout()
381 this.#updateRefetchInterval(this.#computeRefetchInterval())
382 }
383β
384 #clearStaleTimeout(): void {
385 if (this.#staleTimeoutId) {
386 clearTimeout(this.#staleTimeoutId)
387 this.#staleTimeoutId = undefined
388 }
389 }
390β
391 #clearRefetchInterval(): void {
392 if (this.#refetchIntervalId) {
393 clearInterval(this.#refetchIntervalId)
394 this.#refetchIntervalId = undefined
395 }
396 }
397β
398 protected createResult(
399 query: Query<TQueryFnData, TError, TQueryData, TQueryKey>,
400 options: QueryObserverOptions<
401 TQueryFnData,
402 TError,
403 TData,
404 TQueryData,
405 TQueryKey
406 >,
407 ): QueryObserverResult<TData, TError> {
408 const prevQuery = this.#currentQuery
409 const prevOptions = this.options
410 const prevResult = this.#currentResult as
411 | QueryObserverResult<TData, TError>
412 | undefined
413 const prevResultState = this.#currentResultState
414 const prevResultOptions = this.#currentResultOptions
415 const queryChange = query !== prevQuery
416 const queryInitialState = queryChange
417 ? query.state
418 : this.#currentQueryInitialState
419β
420 const { state } = query
421 let { error, errorUpdatedAt, fetchStatus, status } = state
422 let isPlaceholderData = false
423 let data: TData | undefined
424β
425 // Optimistically set result in fetching state if needed
426 if (options._optimisticResults) {
427 const mounted = this.hasListeners()
428β
429 const fetchOnMount = !mounted && shouldFetchOnMount(query, options)
430β
431 const fetchOptionally =
432 mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions)
433β
434 if (fetchOnMount || fetchOptionally) {
435 fetchStatus = canFetch(query.options.networkMode)
436 ? 'fetching'
437 : 'paused'
438 if (!state.dataUpdatedAt) {
439 status = 'pending'
440 }
441 }
442 if (options._optimisticResults === 'isRestoring') {
443 fetchStatus = 'idle'
444 }
445 }
446β
447 // Select data if needed
448 if (options.select && typeof state.data !== 'undefined') {
449 // Memoize select result
450 if (
451 prevResult &&
452 state.data === prevResultState?.data &&
453 options.select === this.#selectFn
454 ) {
455 data = this.#selectResult
456 } else {
457 try {
458 this.#selectFn = options.select
459 data = options.select(state.data)
460 data = replaceData(prevResult?.data, data, options)
461 this.#selectResult = data
462 this.#selectError = null
463 } catch (selectError) {
464 this.#selectError = selectError as TError
465 }
466 }
467 }
468 // Use query data
469 else {
470 data = state.data as unknown as TData
471 }
472β
473 // Show placeholder data if needed
474 if (
475 typeof options.placeholderData !== 'undefined' &&
476 typeof data === 'undefined' &&
477 status === 'pending'
478 ) {
479 let placeholderData
480β
481 // Memoize placeholder data
482 if (
483 prevResult?.isPlaceholderData &&
484 options.placeholderData === prevResultOptions?.placeholderData
485 ) {
486 placeholderData = prevResult.data
487 } else {
488 placeholderData =
489 typeof options.placeholderData === 'function'
490 ? (
491 options.placeholderData as unknown as PlaceholderDataFunction<TQueryData>
492 )(this.#lastDefinedQueryData)
493 : options.placeholderData
494 if (options.select && typeof placeholderData !== 'undefined') {
495 try {
496 placeholderData = options.select(placeholderData)
497 this.#selectError = null
498 } catch (selectError) {
499 this.#selectError = selectError as TError
500 }
501 }
502 }
503β
504 if (typeof placeholderData !== 'undefined') {
505 status = 'success'
506 data = replaceData(
507 prevResult?.data,
508 placeholderData as unknown,
509 options,
510 ) as TData
511 isPlaceholderData = true
512 }
513 }
514β
515 if (this.#selectError) {
516 error = this.#selectError as any
517 data = this.#selectResult
518 errorUpdatedAt = Date.now()
519 status = 'error'
520 }
521β
522 const isFetching = fetchStatus === 'fetching'
523 const isPending = status === 'pending'
524 const isError = status === 'error'
525β
526 const isLoading = isPending && isFetching
527β
528 const result: QueryObserverBaseResult<TData, TError> = {
529 status,
530 fetchStatus,
531 isPending,
532 isSuccess: status === 'success',
533 isError,
534 isInitialLoading: isLoading,
535 isLoading,
536 data,
537 dataUpdatedAt: state.dataUpdatedAt,
538 error,
539 errorUpdatedAt,
540 failureCount: state.fetchFailureCount,
541 failureReason: state.fetchFailureReason,
542 errorUpdateCount: state.errorUpdateCount,
543 isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
544 isFetchedAfterMount:
545 state.dataUpdateCount > queryInitialState.dataUpdateCount ||
546 state.errorUpdateCount > queryInitialState.errorUpdateCount,
547 isFetching,
548 isRefetching: isFetching && !isPending,
549 isLoadingError: isError && state.dataUpdatedAt === 0,
550 isPaused: fetchStatus === 'paused',
551 isPlaceholderData,
552 isRefetchError: isError && state.dataUpdatedAt !== 0,
553 isStale: isStale(query, options),
554 refetch: this.refetch,
555 }
556β
557 return result as QueryObserverResult<TData, TError>
558 }
559β
560 #updateResult(notifyOptions?: NotifyOptions): void {
561 const prevResult = this.#currentResult as
562 | QueryObserverResult<TData, TError>
563 | undefined
564β
565 const nextResult = this.createResult(this.#currentQuery, this.options)
566 this.#currentResultState = this.#currentQuery.state
567 this.#currentResultOptions = this.options
568β
569 // Only notify and update result if something has changed
570 if (shallowEqualObjects(nextResult, prevResult)) {
571 return
572 }
573β
574 if (this.#currentResultState.data !== undefined) {
575 this.#lastDefinedQueryData = this.#currentResultState.data
576 }
577 this.#currentResult = nextResult
578β
579 // Determine which callbacks to trigger
580 const defaultNotifyOptions: NotifyOptions = {}
581β
582 const shouldNotifyListeners = (): boolean => {
583 if (!prevResult) {
584 return true
585 }
586β
587 const { notifyOnChangeProps } = this.options
588β
589 if (
590 notifyOnChangeProps === 'all' ||
591 (!notifyOnChangeProps && !this.#trackedProps.size)
592 ) {
593 return true
594 }
595β
596 const includedProps = new Set(notifyOnChangeProps ?? this.#trackedProps)
597β
598 if (this.options.throwOnError) {
599 includedProps.add('error')
600 }
601β
602 return Object.keys(this.#currentResult).some((key) => {
603 const typedKey = key as keyof QueryObserverResult
604 const changed = this.#currentResult[typedKey] !== prevResult[typedKey]
605 return changed && includedProps.has(typedKey)
606 })
607 }
608β
609 if (notifyOptions?.listeners !== false && shouldNotifyListeners()) {
610 defaultNotifyOptions.listeners = true
611 }
612β
613 this.#notify({ ...defaultNotifyOptions, ...notifyOptions })
614 }
615β
616 #updateQuery(): void {
617 const query = this.#client.getQueryCache().build(this.#client, this.options)
618β
619 if (query === this.#currentQuery) {
620 return
621 }
622β
623 const prevQuery = this.#currentQuery as
624 | Query<TQueryFnData, TError, TQueryData, TQueryKey>
625 | undefined
626 this.#currentQuery = query
627 this.#currentQueryInitialState = query.state
628β
629 if (this.hasListeners()) {
630 prevQuery?.removeObserver(this)
631 query.addObserver(this)
632 }
633 }
634β
635 onQueryUpdate(): void {
636 this.#updateResult()
637β
638 if (this.hasListeners()) {
639 this.#updateTimers()
640 }
641 }
642β
643 #notify(notifyOptions: NotifyOptions): void {
644 notifyManager.batch(() => {
645 // First, trigger the listeners
646 if (notifyOptions.listeners) {
647 this.listeners.forEach((listener) => {
648 listener(this.#currentResult)
649 })
650 }
651β
652 // Then the cache listeners
653 this.#client.getQueryCache().notify({
654 query: this.#currentQuery,
655 type: 'observerResultsUpdated',
656 })
657 })
658 }
659}
660β
661function shouldLoadOnMount(
662 query: Query<any, any, any, any>,
663 options: QueryObserverOptions<any, any, any, any>,
664): boolean {
665 return (
666 options.enabled !== false &&
667 !query.state.dataUpdatedAt &&
668 !(query.state.status === 'error' && options.retryOnMount === false)
669 )
670}
671β
672function shouldFetchOnMount(
673 query: Query<any, any, any, any>,
674 options: QueryObserverOptions<any, any, any, any, any>,
675): boolean {
676 return (
677 shouldLoadOnMount(query, options) ||
678 (query.state.dataUpdatedAt > 0 &&
679 shouldFetchOn(query, options, options.refetchOnMount))
680 )
681}
682β
683function shouldFetchOn(
684 query: Query<any, any, any, any>,
685 options: QueryObserverOptions<any, any, any, any, any>,
686 field: (typeof options)['refetchOnMount'] &
687 (typeof options)['refetchOnWindowFocus'] &
688 (typeof options)['refetchOnReconnect'],
689) {
690 if (options.enabled !== false) {
691 const value = typeof field === 'function' ? field(query) : field
692β
693 return value === 'always' || (value !== false && isStale(query, options))
694 }
695 return false
696}
697β
698function shouldFetchOptionally(
699 query: Query<any, any, any, any>,
700 prevQuery: Query<any, any, any, any>,
701 options: QueryObserverOptions<any, any, any, any, any>,
702 prevOptions: QueryObserverOptions<any, any, any, any, any>,
703): boolean {
704 return (
705 options.enabled !== false &&
706 (query !== prevQuery || prevOptions.enabled === false) &&
707 (!options.suspense || query.state.status !== 'error') &&
708 isStale(query, options)
709 )
710}
711β
712function isStale(
713 query: Query<any, any, any, any>,
714 options: QueryObserverOptions<any, any, any, any, any>,
715): boolean {
716 return query.isStaleByTime(options.staleTime)
717}