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'
11import type { QueryObserverResultReader } from './queryObserver'
12β
13/**
14 * Returns the items of `array1` that are not in `array2`.
15 * @param array1 - The items to filter.
16 * @param array2 - The items to exclude.
17 * @returns A new array with the items of `array1` that are not in `array2`.
18 */
19function difference<T>(array1: Array<T>, array2: Array<T>): Array<T> {
20 const excludeSet = new Set(array2)
21 return array1.filter((x) => !excludeSet.has(x))
22}
23β
24/**
25 * Compares the fields of each result with the result at the same position.
26 * @param result - The current array of observer results.
27 * @param previous - The array from the previous computation, if any.
28 * @returns `true` if the arrays have the same length and equal result fields.
29 */
30function equalResults(
31 result: Array<QueryObserverResult>,
32 previous: Array<QueryObserverResult> | undefined,
33): boolean {
34 return (
35 !!previous &&
36 result.length === previous.length &&
37 result.every((value, index) => shallowEqualObjects(value, previous[index]))
38 )
39}
40β
41type QueriesObserverListener = (result: Array<QueryObserverResult>) => void
42β
43type CombineFn<TCombinedResult> = (
44 result: Array<QueryObserverResult>,
45) => TCombinedResult
46β
47/** A cached reader for multiple query results and their combined value. */
48export interface QueriesObserverResultReader<
49 TCombinedResult,
50> extends QueryObserverResultReader<Array<QueryObserverResult>> {
51 /** Track result properties and combine the results with this reader's options. */
52 combineResult: (result: Array<QueryObserverResult>) => TCombinedResult
53}
54β
55type CombineContext<TCombinedResult> = {
56 result?: Array<QueryObserverResult>
57 combine?: CombineFn<TCombinedResult>
58 value?: TCombinedResult
59 queryHashes?: Array<string>
60}
61β
62/**
63 * Options for a `QueriesObserver` that apply to all of its queries at once.
64 */
65export interface QueriesObserverOptions<
66 TCombinedResult = Array<QueryObserverResult>,
67> {
68 /**
69 * A function that combines the array of `QueryObserverResult`s (one per
70 * observed query) into a single value. The combined value is memoized and
71 * only recomputed when one of the underlying results, the query hashes, or
72 * the `combine` function itself changes.
73 *
74 * Defaults to returning the array of `QueryObserverResult`s unchanged.
75 */
76 combine?: CombineFn<TCombinedResult>
77}
78β
79/**
80 * A `QueriesObserver` watches an array of queries at once, exposing them as
81 * a single array of `QueryObserverResult`s (or, when a `combine` option is
82 * given, as a combined value derived from that array). It manages one
83 * internal `QueryObserver` per query, and is the primitive that framework
84 * adapters (e.g. `useQueries`) build their hooks on top of.
85 * @example
86 * ```ts
87 * const observer = new QueriesObserver(queryClient, [
88 * { queryKey: ['post', 1], queryFn: fetchPost },
89 * { queryKey: ['post', 2], queryFn: fetchPost },
90 * ])
91 *
92 * const unsubscribe = observer.subscribe((result) => {
93 * console.log(result)
94 * })
95 * ```
96 */
97export class QueriesObserver<
98 TCombinedResult = Array<QueryObserverResult>,
99> extends Subscribable<QueriesObserverListener> {
100 #client: QueryClient
101 #result!: Array<QueryObserverResult>
102 #options?: QueriesObserverOptions<TCombinedResult>
103 #observers: Array<QueryObserver>
104 #combinedResult?: TCombinedResult
105 #combineContext: CombineContext<TCombinedResult> = {}
106 #observerMatches: Array<QueryObserverMatch> = []
107 #updatingQueries = false
108β
109 constructor(
110 client: QueryClient,
111 queries: Array<QueryObserverOptions<any, any, any, any, any>>,
112 options?: QueriesObserverOptions<TCombinedResult>,
113 ) {
114 super()
115β
116 this.#client = client
117 this.#options = options
118 this.#observers = []
119 this.#result = []
120β
121 this.setQueries(queries)
122 }
123β
124 protected override onSubscribe(): void {
125 if (this.listeners.size === 1) {
126 this.#observers.forEach((observer) => {
127 observer.subscribe((result) => {
128 this.#onUpdate(observer, result)
129 })
130 })
131 }
132 }
133β
134 protected override onUnsubscribe(): void {
135 if (!this.listeners.size) {
136 this.destroy()
137 }
138 }
139β
140 /**
141 * Stops observing all queries: clears all listeners and destroys every
142 * underlying `QueryObserver` this observer manages.
143 */
144 destroy(): void {
145 this.listeners = new Set()
146 this.#observers.forEach((observer) => {
147 observer.destroy()
148 })
149 }
150β
151 /**
152 * Replaces the set of queries being observed. Existing `QueryObserver`s
153 * are reused for queries that match an already-observed query hash;
154 * observers for queries that are no longer present are destroyed, and new
155 * observers are created and subscribed to for newly added queries.
156 * @param queries - The options of the queries to observe.
157 * @param options - Replaces the observer's options, e.g. its `combine` function.
158 * @example
159 * ```ts
160 * observer.setQueries([
161 * { queryKey: ['post', 1], queryFn: fetchPost },
162 * { queryKey: ['post', 3], queryFn: fetchPost },
163 * ])
164 * ```
165 */
166 setQueries(
167 queries: Array<QueryObserverOptions>,
168 options?: QueriesObserverOptions<TCombinedResult>,
169 ): void {
170 this.#setQueries(this.#findMatchingObservers(queries), options)
171 }
172β
173 #setQueries(
174 newObserverMatches: Array<QueryObserverMatch>,
175 options?: QueriesObserverOptions<TCombinedResult>,
176 ): void {
177 this.#options = options
178β
179 if (process.env.NODE_ENV !== 'production') {
180 const queryHashes = newObserverMatches.map(
181 (match) => match.defaultedQueryOptions.queryHash,
182 )
183 if (new Set(queryHashes).size !== queryHashes.length) {
184 console.warn(
185 '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.',
186 )
187 }
188 }
189β
190 notifyManager.batch(() => {
191 const prevObservers = this.#observers
192β
193 // Apply all options before combining or notifying with the new results.
194 this.#updatingQueries = true
195 try {
196 newObserverMatches.forEach((match) => {
197 if (match.reader) {
198 match.reader.commit()
199 } else {
200 match.observer.setOptions(match.defaultedQueryOptions)
201 }
202 })
203 } finally {
204 this.#updatingQueries = false
205 }
206β
207 const newObservers = newObserverMatches.map((match) => match.observer)
208 const newResult = newObservers.map((observer) =>
209 observer.getCurrentResult(),
210 )
211β
212 const hasLengthChange = prevObservers.length !== newObservers.length
213 const hasIndexChange = newObservers.some(
214 (observer, index) => observer !== prevObservers[index],
215 )
216 const hasStructuralChange = hasLengthChange || hasIndexChange
217β
218 const hasResultChange = hasStructuralChange
219 ? true
220 : newResult.some((result, index) => {
221 const prev = this.#result[index]
222 return !prev || !shallowEqualObjects(result, prev)
223 })
224β
225 if (!hasStructuralChange && !hasResultChange) return
226β
227 if (hasStructuralChange) {
228 this.#observerMatches = newObserverMatches.map(
229 ({ defaultedQueryOptions, observer }) => ({
230 defaultedQueryOptions,
231 observer,
232 }),
233 )
234 this.#observers = newObservers
235 }
236β
237 this.#result = newResult
238β
239 if (!this.hasListeners()) return
240β
241 if (hasStructuralChange) {
242 difference(prevObservers, newObservers).forEach((observer) => {
243 observer.destroy()
244 })
245 difference(newObservers, prevObservers).forEach((observer) => {
246 observer.subscribe((result) => {
247 this.#onUpdate(observer, result)
248 })
249 })
250 }
251β
252 this.#notify()
253 })
254 }
255β
256 /**
257 * Returns the most recently computed array of `QueryObserverResult`s, one
258 * per observed query, in the same order as the queries passed to the
259 * constructor or `setQueries`.
260 * @returns The current results.
261 * @example
262 * ```ts
263 * const results = observer.getCurrentResult()
264 * const data = results.map((result) => result.data)
265 * ```
266 */
267 getCurrentResult(): Array<QueryObserverResult> {
268 return this.#result
269 }
270β
271 /**
272 * Returns the underlying `Query` instances currently being observed, in
273 * the same order as the queries passed to the constructor or `setQueries`.
274 * @returns The observed queries.
275 */
276 getQueries() {
277 return this.#observers.map((observer) => observer.getCurrentQuery())
278 }
279β
280 /**
281 * Returns the underlying `QueryObserver` instances this observer manages,
282 * in the same order as the queries passed to the constructor or
283 * `setQueries`.
284 * @returns The managed query observers.
285 */
286 getObservers() {
287 return this.#observers
288 }
289β
290 /**
291 * Creates a reader for the supplied queries and combine function. Reads keep
292 * result and combine caches local until commit applies the queries and reuses
293 * their computation state. Abandoned readers do not change active observers.
294 * @param queries - The options of the queries to read and commit.
295 * @param options - The combine function used for this reader.
296 * @returns A reader with local snapshot and combine caches.
297 */
298 createResultReader(
299 queries: Array<QueryObserverOptions<any, any, any, any, any>>,
300 options?: QueriesObserverOptions<TCombinedResult>,
301 ): QueriesObserverResultReader<TCombinedResult> {
302 const matches = this.#findMatchingObservers(queries).map((match) => ({
303 ...match,
304 reader: match.observer.createResultReader(match.defaultedQueryOptions),
305 }))
306 const queryHashes = matches.map(
307 (match) => match.defaultedQueryOptions.queryHash,
308 )
309 const combine = options?.combine
310 const context = { ...this.#combineContext }
311 let result = this.#result
312β
313 const getSnapshot = () => {
314 const nextResult = matches.map((match) => match.reader.getSnapshot())
315 if (!shallowEqualObjects(nextResult, result)) {
316 result = nextResult
317 }
318 return result
319 }
320β
321 return {
322 getSnapshot,
323 combineResult: (input) => {
324 // Notifications may have already combined these results.
325 const committed = this.#combineContext
326 if (
327 committed.combine === combine &&
328 equalResults(input, committed.result) &&
329 shallowEqualObjects(queryHashes, committed.queryHashes)
330 ) {
331 Object.assign(context, committed)
332 }
333 return this.#combineResult(
334 this.#trackResult(input, matches),
335 combine,
336 queryHashes,
337 context,
338 input,
339 )
340 },
341 commit: () => {
342 this.#combineContext = { ...context }
343 this.#setQueries(matches, { combine })
344 if (
345 this.#options?.combine === combine &&
346 equalResults(this.#result, context.result)
347 ) {
348 this.#combinedResult = context.value
349 }
350 },
351 }
352 }
353β
354 /**
355 * The `QueriesObserver` counterpart of {@link QueryObserver#getOptimisticResult} β computes
356 * the result for the given (already-defaulted) queries right now, synchronously. Called by
357 * framework adapters (e.g. `useQueries`) ahead of subscribing, returning a tuple of the raw
358 * per-query results, a function to compute the combined result from them, and a function to
359 * wrap the results for property-access tracking.
360 * @param queries - The defaulted options of the queries to compute the result for.
361 * @param combine - The `combine` function used by the returned `combineResult`, if any.
362 * @returns A tuple of the per-query results, a function that computes the combined result, and a
363 * function that returns the results wrapped for property-access tracking.
364 * @deprecated Use `createResultReader` instead.
365 */
366 getOptimisticResult(
367 queries: Array<QueryObserverOptions>,
368 combine: CombineFn<TCombinedResult> | undefined,
369 ): [
370 rawResult: Array<QueryObserverResult>,
371 combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult,
372 trackResult: () => Array<QueryObserverResult>,
373 ] {
374 const matches = this.#findMatchingObservers(queries)
375 const result = matches.map((match) =>
376 match.observer
377 .createResultReader(match.defaultedQueryOptions)
378 .getSnapshot(),
379 )
380 const queryHashes = matches.map(
381 (match) => match.defaultedQueryOptions.queryHash,
382 )
383β
384 return [
385 result,
386 (r?: Array<QueryObserverResult>) => {
387 const combined = this.#combineResult(r ?? result, combine, queryHashes)
388 this.#combinedResult = combined
389 return combined
390 },
391 () => {
392 return this.#trackResult(result, matches)
393 },
394 ]
395 }
396β
397 #trackResult(
398 result: Array<QueryObserverResult>,
399 matches: Array<QueryObserverMatch>,
400 ) {
401 const trackedProps = new Set<keyof QueryObserverResult>()
402β
403 return matches.map((match, index) => {
404 const observerResult = result[index]!
405 return !match.defaultedQueryOptions.notifyOnChangeProps
406 ? match.observer.trackResult(observerResult, (accessedProp) => {
407 // track property on all observers to ensure proper (synchronized) tracking (#7000)
408 if (!trackedProps.has(accessedProp)) {
409 trackedProps.add(accessedProp)
410 matches.forEach((m) => {
411 m.observer.trackProp(accessedProp)
412 })
413 }
414 })
415 : observerResult
416 })
417 }
418β
419 #combineResult(
420 input: Array<QueryObserverResult>,
421 combine: CombineFn<TCombinedResult> | undefined,
422 queryHashes?: Array<string>,
423 context = this.#combineContext,
424 result = this.#result,
425 ): TCombinedResult {
426 if (combine) {
427 const queryHashesChanged =
428 queryHashes !== undefined &&
429 context.queryHashes !== undefined &&
430 !shallowEqualObjects(queryHashes, context.queryHashes)
431β
432 if (
433 !equalResults(result, context.result) ||
434 queryHashesChanged ||
435 combine !== context.combine
436 ) {
437 context.value = replaceEqualDeep(context.value, combine(input))
438 context.combine = combine
439 context.result = result
440 if (queryHashes !== undefined) {
441 context.queryHashes = queryHashes
442 }
443 }
444β
445 return context.value as TCombinedResult
446 }
447 return input as any
448 }
449β
450 #shouldSkipCombine(): boolean {
451 return (
452 !this.#options?.combine ||
453 this.#observers.some((observer, index) => {
454 return (
455 observer.options.suspense && this.#result[index]?.data === undefined
456 )
457 })
458 )
459 }
460β
461 #findMatchingObservers(
462 queries: Array<QueryObserverOptions>,
463 ): Array<QueryObserverMatch> {
464 const prevObserversMap = new Map<string, Array<QueryObserver>>()
465β
466 this.#observers.forEach((observer) => {
467 const key = observer.options.queryHash
468 if (!key) return
469β
470 const previousObservers = prevObserversMap.get(key)
471β
472 if (previousObservers) {
473 previousObservers.push(observer)
474 } else {
475 prevObserversMap.set(key, [observer])
476 }
477 })
478β
479 const observers: Array<QueryObserverMatch> = []
480β
481 queries.forEach((options) => {
482 const defaultedOptions = this.#client.defaultQueryOptions(options)
483 const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift()
484 const observer =
485 match ?? new QueryObserver(this.#client, defaultedOptions)
486β
487 observers.push({
488 defaultedQueryOptions: defaultedOptions,
489 observer,
490 })
491 })
492β
493 return observers
494 }
495β
496 #onUpdate(observer: QueryObserver, result: QueryObserverResult): void {
497 if (this.#updatingQueries) return
498β
499 const index = this.#observers.indexOf(observer)
500 if (index !== -1) {
501 this.#result = this.#result.slice()
502 this.#result[index] = result
503 this.#notify()
504 }
505 }
506β
507 #notify(): void {
508 if (this.hasListeners()) {
509 const shouldSkipCombine = this.#shouldSkipCombine()
510 const previousResult = this.#combinedResult
511 const newResult = shouldSkipCombine
512 ? previousResult
513 : this.#combineResult(
514 this.#trackResult(this.#result, this.#observerMatches),
515 this.#options?.combine,
516 )
517β
518 this.#combinedResult = newResult
519 if (shouldSkipCombine || previousResult !== newResult) {
520 notifyManager.batch(() => {
521 this.listeners.forEach((listener) => {
522 listener(this.#result)
523 })
524 })
525 }
526 }
527 }
528}
529β
530type QueryObserverMatch = {
531 defaultedQueryOptions: DefaultedQueryObserverOptions
532 observer: QueryObserver
533 reader?: QueryObserverResultReader<QueryObserverResult>
534}