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