Open History to see the last commit
1import { notifyManager } from './notifyManager'
2import { QueryObserver } from './queryObserver'
3import { Subscribable } from './subscribable'
4import { replaceEqualDeep, shallowEqualObjects } from './utils'
5import type {
6 DefaultedQueryObserverOptions,
7 QueryObserverOptions,
8 QueryObserverResult,
9} from './types'
10import type { QueryClient } from './queryClient'
11β
12/**
13 * Returns the items of `array1` that are not in `array2`.
14 * @param array1 - The items to filter.
15 * @param array2 - The items to exclude.
16 * @returns A new array with the items of `array1` that are not in `array2`.
17 */
18function difference<T>(array1: Array<T>, array2: Array<T>): Array<T> {
19 const excludeSet = new Set(array2)
20 return array1.filter((x) => !excludeSet.has(x))
21}
22β
23type QueriesObserverListener = (result: Array<QueryObserverResult>) => void
24β
25type CombineFn<TCombinedResult> = (
26 result: Array<QueryObserverResult>,
27) => TCombinedResult
28β
29/**
30 * Options for a `QueriesObserver` that apply to all of its queries at once.
31 */
32export interface QueriesObserverOptions<
33 TCombinedResult = Array<QueryObserverResult>,
34> {
35 /**
36 * A function that combines the array of `QueryObserverResult`s (one per
37 * observed query) into a single value. The combined value is memoized and
38 * only recomputed when one of the underlying results, the query hashes, or
39 * the `combine` function itself changes.
40 *
41 * Defaults to returning the array of `QueryObserverResult`s unchanged.
42 */
43 combine?: CombineFn<TCombinedResult>
44}
45β
46/**
47 * A `QueriesObserver` watches an array of queries at once, exposing them as
48 * a single array of `QueryObserverResult`s (or, when a `combine` option is
49 * given, as a combined value derived from that array). It manages one
50 * internal `QueryObserver` per query, and is the primitive that framework
51 * adapters (e.g. `useQueries`) build their hooks on top of.
52 * @example
53 * ```ts
54 * const observer = new QueriesObserver(queryClient, [
55 * { queryKey: ['post', 1], queryFn: fetchPost },
56 * { queryKey: ['post', 2], queryFn: fetchPost },
57 * ])
58 *
59 * const unsubscribe = observer.subscribe((result) => {
60 * console.log(result)
61 * })
62 * ```
63 */
64export class QueriesObserver<
65 TCombinedResult = Array<QueryObserverResult>,
66> extends Subscribable<QueriesObserverListener> {
67 #client: QueryClient
68 #result!: Array<QueryObserverResult>
69 #queries: Array<QueryObserverOptions>
70 #options?: QueriesObserverOptions<TCombinedResult>
71 #observers: Array<QueryObserver>
72 #combinedResult!: TCombinedResult
73 #lastCombine?: CombineFn<TCombinedResult>
74 #lastResult?: Array<QueryObserverResult>
75 #lastQueryHashes?: Array<string>
76 #observerMatches: Array<QueryObserverMatch> = []
77β
78 constructor(
79 client: QueryClient,
80 queries: Array<QueryObserverOptions<any, any, any, any, any>>,
81 options?: QueriesObserverOptions<TCombinedResult>,
82 ) {
83 super()
84β
85 this.#client = client
86 this.#options = options
87 this.#queries = []
88 this.#observers = []
89 this.#result = []
90β
91 this.setQueries(queries)
92 }
93β
94 protected override onSubscribe(): void {
95 if (this.listeners.size === 1) {
96 this.#observers.forEach((observer) => {
97 observer.subscribe((result) => {
98 this.#onUpdate(observer, result)
99 })
100 })
101 }
102 }
103β
104 protected override onUnsubscribe(): void {
105 if (!this.listeners.size) {
106 this.destroy()
107 }
108 }
109β
110 /**
111 * Stops observing all queries: clears all listeners and destroys every
112 * underlying `QueryObserver` this observer manages.
113 */
114 destroy(): void {
115 this.listeners = new Set()
116 this.#observers.forEach((observer) => {
117 observer.destroy()
118 })
119 }
120β
121 /**
122 * Replaces the set of queries being observed. Existing `QueryObserver`s
123 * are reused for queries that match an already-observed query hash;
124 * observers for queries that are no longer present are destroyed, and new
125 * observers are created and subscribed to for newly added queries.
126 * @param queries - The options of the queries to observe.
127 * @param options - Replaces the observer's options, e.g. its `combine` function.
128 * @example
129 * ```ts
130 * observer.setQueries([
131 * { queryKey: ['post', 1], queryFn: fetchPost },
132 * { queryKey: ['post', 3], queryFn: fetchPost },
133 * ])
134 * ```
135 */
136 setQueries(
137 queries: Array<QueryObserverOptions>,
138 options?: QueriesObserverOptions<TCombinedResult>,
139 ): void {
140 this.#queries = queries
141 this.#options = options
142β
143 if (process.env.NODE_ENV !== 'production') {
144 const queryHashes = queries.map(
145 (query) => this.#client.defaultQueryOptions(query).queryHash,
146 )
147 if (new Set(queryHashes).size !== queryHashes.length) {
148 console.warn(
149 '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.',
150 )
151 }
152 }
153β
154 notifyManager.batch(() => {
155 const prevObservers = this.#observers
156β
157 const newObserverMatches = this.#findMatchingObservers(this.#queries)
158β
159 // set options for the new observers to notify of changes
160 newObserverMatches.forEach((match) =>
161 match.observer.setOptions(match.defaultedQueryOptions),
162 )
163β
164 const newObservers = newObserverMatches.map((match) => match.observer)
165 const newResult = newObservers.map((observer) =>
166 observer.getCurrentResult(),
167 )
168β
169 const hasLengthChange = prevObservers.length !== newObservers.length
170 const hasIndexChange = newObservers.some(
171 (observer, index) => observer !== prevObservers[index],
172 )
173 const hasStructuralChange = hasLengthChange || hasIndexChange
174β
175 const hasResultChange = hasStructuralChange
176 ? true
177 : newResult.some((result, index) => {
178 const prev = this.#result[index]
179 return !prev || !shallowEqualObjects(result, prev)
180 })
181β
182 if (!hasStructuralChange && !hasResultChange) return
183β
184 if (hasStructuralChange) {
185 this.#observerMatches = newObserverMatches
186 this.#observers = newObservers
187 }
188β
189 this.#result = newResult
190β
191 if (!this.hasListeners()) return
192β
193 if (hasStructuralChange) {
194 difference(prevObservers, newObservers).forEach((observer) => {
195 observer.destroy()
196 })
197 difference(newObservers, prevObservers).forEach((observer) => {
198 observer.subscribe((result) => {
199 this.#onUpdate(observer, result)
200 })
201 })
202 }
203β
204 this.#notify()
205 })
206 }
207β
208 /**
209 * Returns the most recently computed array of `QueryObserverResult`s, one
210 * per observed query, in the same order as the queries passed to the
211 * constructor or `setQueries`.
212 * @returns The current results.
213 * @example
214 * ```ts
215 * const results = observer.getCurrentResult()
216 * const data = results.map((result) => result.data)
217 * ```
218 */
219 getCurrentResult(): Array<QueryObserverResult> {
220 return this.#result
221 }
222β
223 /**
224 * Returns the underlying `Query` instances currently being observed, in
225 * the same order as the queries passed to the constructor or `setQueries`.
226 * @returns The observed queries.
227 */
228 getQueries() {
229 return this.#observers.map((observer) => observer.getCurrentQuery())
230 }
231β
232 /**
233 * Returns the underlying `QueryObserver` instances this observer manages,
234 * in the same order as the queries passed to the constructor or
235 * `setQueries`.
236 * @returns The managed query observers.
237 */
238 getObservers() {
239 return this.#observers
240 }
241β
242 /**
243 * The `QueriesObserver` counterpart of {@link QueryObserver#getOptimisticResult} β computes
244 * the result for the given (already-defaulted) queries right now, synchronously. Called by
245 * framework adapters (e.g. `useQueries`) ahead of subscribing, returning a tuple of the raw
246 * per-query results, a function to compute the combined result from them, and a function to
247 * wrap the results for property-access tracking.
248 * @param queries - The defaulted options of the queries to compute the result for.
249 * @param combine - The `combine` function used by the returned `combineResult`, if any.
250 * @returns A tuple of the per-query results, a function that computes the combined result, and a
251 * function that returns the results wrapped for property-access tracking.
252 */
253 getOptimisticResult(
254 queries: Array<QueryObserverOptions>,
255 combine: CombineFn<TCombinedResult> | undefined,
256 ): [
257 rawResult: Array<QueryObserverResult>,
258 combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult,
259 trackResult: () => Array<QueryObserverResult>,
260 ] {
261 const matches = this.#findMatchingObservers(queries)
262 const result = matches.map((match) =>
263 match.observer.getOptimisticResult(match.defaultedQueryOptions),
264 )
265 const queryHashes = matches.map(
266 (match) => match.defaultedQueryOptions.queryHash,
267 )
268β
269 return [
270 result,
271 (r?: Array<QueryObserverResult>) => {
272 return this.#combineResult(r ?? result, combine, queryHashes)
273 },
274 () => {
275 return this.#trackResult(result, matches)
276 },
277 ]
278 }
279β
280 #trackResult(
281 result: Array<QueryObserverResult>,
282 matches: Array<QueryObserverMatch>,
283 ) {
284 const trackedProps = new Set<keyof QueryObserverResult>()
285β
286 return matches.map((match, index) => {
287 const observerResult = result[index]!
288 return !match.defaultedQueryOptions.notifyOnChangeProps
289 ? match.observer.trackResult(observerResult, (accessedProp) => {
290 // track property on all observers to ensure proper (synchronized) tracking (#7000)
291 if (!trackedProps.has(accessedProp)) {
292 trackedProps.add(accessedProp)
293 matches.forEach((m) => {
294 m.observer.trackProp(accessedProp)
295 })
296 }
297 })
298 : observerResult
299 })
300 }
301β
302 #combineResult(
303 input: Array<QueryObserverResult>,
304 combine: CombineFn<TCombinedResult> | undefined,
305 queryHashes?: Array<string>,
306 ): TCombinedResult {
307 if (combine) {
308 const lastHashes = this.#lastQueryHashes
309 const queryHashesChanged =
310 queryHashes !== undefined &&
311 lastHashes !== undefined &&
312 (lastHashes.length !== queryHashes.length ||
313 queryHashes.some((hash, i) => hash !== lastHashes[i]))
314β
315 if (
316 this.#result !== this.#lastResult ||
317 queryHashesChanged ||
318 combine !== this.#lastCombine
319 ) {
320 this.#lastCombine = combine
321 this.#lastResult = this.#result
322β
323 if (queryHashes !== undefined) {
324 this.#lastQueryHashes = queryHashes
325 }
326 this.#combinedResult = replaceEqualDeep(
327 this.#combinedResult,
328 combine(input),
329 )
330 }
331β
332 return this.#combinedResult
333 }
334 return input as any
335 }
336β
337 #shouldSkipCombine(): boolean {
338 return (
339 !this.#options?.combine ||
340 this.#observers.some((observer, index) => {
341 return (
342 observer.options.suspense && this.#result[index]?.data === undefined
343 )
344 })
345 )
346 }
347β
348 #findMatchingObservers(
349 queries: Array<QueryObserverOptions>,
350 ): Array<QueryObserverMatch> {
351 const prevObserversMap = new Map<string, Array<QueryObserver>>()
352β
353 this.#observers.forEach((observer) => {
354 const key = observer.options.queryHash
355 if (!key) return
356β
357 const previousObservers = prevObserversMap.get(key)
358β
359 if (previousObservers) {
360 previousObservers.push(observer)
361 } else {
362 prevObserversMap.set(key, [observer])
363 }
364 })
365β
366 const observers: Array<QueryObserverMatch> = []
367β
368 queries.forEach((options) => {
369 const defaultedOptions = this.#client.defaultQueryOptions(options)
370 const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift()
371 const observer =
372 match ?? new QueryObserver(this.#client, defaultedOptions)
373β
374 observers.push({
375 defaultedQueryOptions: defaultedOptions,
376 observer,
377 })
378 })
379β
380 return observers
381 }
382β
383 #onUpdate(observer: QueryObserver, result: QueryObserverResult): void {
384 const index = this.#observers.indexOf(observer)
385 if (index !== -1) {
386 this.#result = this.#result.slice()
387 this.#result[index] = result
388 this.#notify()
389 }
390 }
391β
392 #notify(): void {
393 if (this.hasListeners()) {
394 const shouldSkipCombine = this.#shouldSkipCombine()
395 const previousResult = this.#combinedResult
396 const newResult = shouldSkipCombine
397 ? previousResult
398 : this.#combineResult(
399 this.#trackResult(this.#result, this.#observerMatches),
400 this.#options?.combine,
401 )
402β
403 if (shouldSkipCombine || previousResult !== newResult) {
404 notifyManager.batch(() => {
405 this.listeners.forEach((listener) => {
406 listener(this.#result)
407 })
408 })
409 }
410 }
411 }
412}
413β
414type QueryObserverMatch = {
415 defaultedQueryOptions: DefaultedQueryObserverOptions
416 observer: QueryObserver
417}