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

queryObserverResultTracker.ts

44 lines1.4 KB

1type TrackableQueryObserver<TResult extends object> = {
2 options: { notifyOnChangeProps?: unknown }
3 trackResult: (result: TResult) => unknown
4}
5​
6/**
7 * Wraps observer results with property tracking when `notifyOnChangeProps` is
8 * not set, so the observer only notifies about the properties the host reads.
9 */
10export class QueryObserverResultTracker<TResult extends object> {
11 private result: TResult | undefined
12 private usesTracking = false
13​
14 /** Forgets the last result, so the next `update` returns a result again. */
15 reset(): void {
16 this.result = undefined
17 this.usesTracking = false
18 }
19​
20 /**
21 * Returns the result to expose, tracked through the observer when it uses
22 * property tracking.
23 *
24 * @param observer - The observer the result comes from, if any.
25 * @param result - The latest result of the observer.
26 * @returns The result to expose, or `undefined` if neither the result nor the
27 * tracking mode changed since the last call.
28 */
29 update(
30 observer: TrackableQueryObserver<TResult> | undefined,
31 result: TResult,
32 ): TResult | undefined {
33 const usesTracking = !!observer && !observer.options.notifyOnChangeProps
34​
35 if (Object.is(this.result, result) && this.usesTracking === usesTracking) {
36 return undefined
37 }
38​
39 this.result = result
40 this.usesTracking = usesTracking
41​
42 return usesTracking ? (observer.trackResult(result) as TResult) : result
43 }