Open History to see the last commit
1import { notifyManager } from './notifyManager'
2import { QueryObserver } from './queryObserver'
3import { Subscribable } from './subscribable'
4import {
5 replaceEqualDeep,
6 shallowEqualObjects,
7 shouldThrowError,
8} from './utils'
9import type { QueryClient } from './queryClient'
10import type {
11 DefaultedQueryObserverOptions,
12 QueryObserverOptions,
13 QueryObserverResult,
14} from './types'
15β
16/**
17 * Returns the items of `array1` that are not in `array2`.
18 * @param array1 - The items to filter.
19 * @param array2 - The items to exclude.
20 * @returns A new array with the items of `array1` that are not in `array2`.
21 */
22function difference<T>(array1: Array<T>, array2: Array<T>): Array<T> {
23 const excludeSet = new Set(array2)
24 return array1.filter((x) => !excludeSet.has(x))
25}
26β
27type QueriesObserverListener = (result: Array<QueryObserverResult>) => void
28β
29type CombineFn<TCombinedResult> = (
30 result: Array<QueryObserverResult>,
31) => TCombinedResult
32β
33/**
34 * Options for a `QueriesObserver` that apply to all of its queries at once.
35 */
36export interface QueriesObserverOptions<
37 TCombinedResult = Array<QueryObserverResult>,
38> {
39 /**
40 * A function that combines the array of `QueryObserverResult`s (one per
41 * observed query) into a single value. The combined value is memoized and
42 * only recomputed when one of the underlying results, the query hashes, or
43 * the `combine` function itself changes.
44 *
45 * Defaults to returning the array of `QueryObserverResult`s unchanged.
46 */
47 combine?: CombineFn<TCombinedResult>
48}
49β
50/**
51 * A `QueriesObserver` watches an array of queries at once, exposing them as
52 * a single array of `QueryObserverResult`s (or, when a `combine` option is
53 * given, as a combined value derived from that array). It manages one
54 * internal `QueryObserver` per query, and is the primitive that framework
55 * adapters (e.g. `useQueries`) build their hooks on top of.
56 * @example
57 * ```ts
58 * const observer = new QueriesObserver(queryClient, [
59 * { queryKey: ['post', 1], queryFn: fetchPost },
60 * { queryKey: ['post', 2], queryFn: fetchPost },
61 * ])
62 *
63 * const unsubscribe = observer.subscribe((result) => {
64 * console.log(result)
65 * })
66 * ```
67 */
68export class QueriesObserver<
69 TCombinedResult = Array<QueryObserverResult>,
70> extends Subscribable<QueriesObserverListener> {
71 #client: QueryClient
72 #result!: Array<QueryObserverResult>
73 #queries: Array<QueryObserverOptions>
74 #options?: QueriesObserverOptions<TCombinedResult>
75 #observers: Array<QueryObserver>
76 #combinedResult!: TCombinedResult
77 #lastCombine?: CombineFn<TCombinedResult>
78 #lastResult?: Array<QueryObserverResult>
79 #lastQueryHashes?: Array<string>
80 #observerMatches: Array<QueryObserverMatch> = []
81β
82 constructor(
83 client: QueryClient,
84 queries: Array<QueryObserverOptions<any, any, any, any, any>>,
85 options?: QueriesObserverOptions<TCombinedResult>,
86 ) {
87 super()
88β
89 this.#client = client
90 this.#options = options
91 this.#queries = []
92 this.#observers = []
93 this.#result = []
94β
95 this.setQueries(queries)
96 }
97β
98 protected override onSubscribe(): void {
99 if (this.listeners.size === 1) {
100 this.#observers.forEach((observer) => this.#subscribeTo(observer))
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 this.#subscribeTo(observer),
199 )
200 }
201β
202 this.#notify()
203 })
204 }
205β
206 /**
207 * Returns the most recently computed array of `QueryObserverResult`s, one
208 * per observed query, in the same order as the queries passed to the
209 * constructor or `setQueries`.
210 * @returns The current results.
211 * @example
212 * ```ts
213 * const results = observer.getCurrentResult()
214 * const data = results.map((result) => result.data)
215 * ```
216 */
217 getCurrentResult(): Array<QueryObserverResult> {
218 return this.#result
219 }
220β
221 /**
222 * Returns the underlying `Query` instances currently being observed, in
223 * the same order as the queries passed to the constructor or `setQueries`.
224 * @returns The observed queries.
225 */
226 getQueries() {
227 return this.#observers.map((observer) => observer.getCurrentQuery())
228 }
229β
230 /**
231 * Returns the underlying `QueryObserver` instances this observer manages,
232 * in the same order as the queries passed to the constructor or
233 * `setQueries`.
234 * @returns The managed query observers.
235 */
236 getObservers() {
237 return this.#observers
238 }
239β
240 /**
241 * The `QueriesObserver` counterpart of {@link QueryObserver#getOptimisticResult} β computes
242 * the result for the given (already-defaulted) queries right now, synchronously. Called by
243 * framework adapters (e.g. `useQueries`) ahead of subscribing, returning a tuple of the raw
244 * per-query results, a function to compute the combined result from them, and a function to
245 * wrap the results for property-access tracking. When the queries match the observed ones, the
246 * results also become the current result, so a later `setQueries` call with the same queries
247 * does not notify the listeners about them.
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 // The observers now hold the optimistic results as their current results.
266 // Hold them here too, so that `setQueries` does not find a change (and
267 // notify) for results that the caller already has.
268 if (
269 matches.length === this.#observers.length &&
270 matches.some(
271 (match, index) =>
272 match.observer.getCurrentResult() !== this.#result[index],
273 ) &&
274 matches.every((match, index) => match.observer === this.#observers[index])
275 ) {
276 this.#result = matches.map((match) => match.observer.getCurrentResult())
277 }
278 const queryHashes = matches.map(
279 (match) => match.defaultedQueryOptions.queryHash,
280 )
281β
282 return [
283 result,
284 (r?: Array<QueryObserverResult>) => {
285 return this.#combineResult(r ?? result, combine, queryHashes)
286 },
287 () => {
288 return this.#trackResult(result, matches)
289 },
290 ]
291 }
292β
293 #trackResult(
294 result: Array<QueryObserverResult>,
295 matches: Array<QueryObserverMatch>,
296 ) {
297 const trackedProps = new Set<keyof QueryObserverResult>()
298β
299 return matches.map((match, index) => {
300 const observerResult = result[index]!
301 return !match.defaultedQueryOptions.notifyOnChangeProps
302 ? match.observer.trackResult(observerResult, (accessedProp) => {
303 // track property on all observers to ensure proper (synchronized) tracking (#7000)
304 if (!trackedProps.has(accessedProp)) {
305 trackedProps.add(accessedProp)
306 matches.forEach((m) => {
307 m.observer.trackProp(accessedProp)
308 })
309 }
310 })
311 : observerResult
312 })
313 }
314β
315 #combineResult(
316 input: Array<QueryObserverResult>,
317 combine: CombineFn<TCombinedResult> | undefined,
318 queryHashes?: Array<string>,
319 ): TCombinedResult {
320 if (combine) {
321 const lastHashes = this.#lastQueryHashes
322 const queryHashesChanged =
323 queryHashes !== undefined &&
324 lastHashes !== undefined &&
325 (lastHashes.length !== queryHashes.length ||
326 queryHashes.some((hash, i) => hash !== lastHashes[i]))
327β
328 if (
329 this.#result !== this.#lastResult ||
330 queryHashesChanged ||
331 combine !== this.#lastCombine
332 ) {
333 this.#lastCombine = combine
334 this.#lastResult = this.#result
335β
336 if (queryHashes !== undefined) {
337 this.#lastQueryHashes = queryHashes
338 }
339 this.#combinedResult = replaceEqualDeep(
340 this.#combinedResult,
341 combine(input),
342 )
343 }
344β
345 return this.#combinedResult
346 }
347 return input as any
348 }
349β
350 #shouldSkipCombine(): boolean {
351 return (
352 !this.#options?.combine ||
353 this.#observers.some((observer, index) => {
354 const result = this.#result[index]
355 return (
356 (observer.options.suspense && result?.data === undefined) ||
357 (!!result?.isError &&
358 !result.isFetching &&
359 shouldThrowError(observer.options.throwOnError, [
360 result.error,
361 observer.getCurrentQuery(),
362 ]))
363 )
364 })
365 )
366 }
367β
368 #findMatchingObservers(
369 queries: Array<QueryObserverOptions>,
370 ): Array<QueryObserverMatch> {
371 const prevObserversMap = new Map<string, Array<QueryObserver>>()
372β
373 this.#observers.forEach((observer) => {
374 const key = observer.options.queryHash
375 if (!key) return
376β
377 const previousObservers = prevObserversMap.get(key)
378β
379 if (previousObservers) {
380 previousObservers.push(observer)
381 } else {
382 prevObserversMap.set(key, [observer])
383 }
384 })
385β
386 const observers: Array<QueryObserverMatch> = []
387β
388 queries.forEach((options) => {
389 const defaultedOptions = this.#client.defaultQueryOptions(options)
390 const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift()
391 const observer =
392 match ?? new QueryObserver(this.#client, defaultedOptions)
393β
394 observers.push({
395 defaultedQueryOptions: defaultedOptions,
396 observer,
397 })
398 })
399β
400 return observers
401 }
402β
403 #subscribeTo(observer: QueryObserver): void {
404 // Create the listener here, not in `setQueries`: a listener created there
405 // keeps the previous observers, and their queries, alive (#12656)
406 observer.subscribe((result) => {
407 this.#onUpdate(observer, result)
408 })
409 }
410β
411 #onUpdate(observer: QueryObserver, result: QueryObserverResult): void {
412 const index = this.#observers.indexOf(observer)
413 if (index !== -1) {
414 this.#result = this.#result.slice()
415 this.#result[index] = result
416 this.#notify()
417 }
418 }
419β
420 #notify(): void {
421 if (this.hasListeners()) {
422 const shouldSkipCombine = this.#shouldSkipCombine()
423 const previousResult = this.#combinedResult
424 const newResult = shouldSkipCombine
425 ? previousResult
426 : this.#combineResult(
427 this.#trackResult(this.#result, this.#observerMatches),
428 this.#options?.combine,
429 this.#observerMatches.map(
430 (match) => match.defaultedQueryOptions.queryHash,
431 ),
432 )
433β
434 if (shouldSkipCombine || previousResult !== newResult) {
435 notifyManager.batch(() => {
436 this.listeners.forEach((listener) => {
437 listener(this.#result)
438 })
439 })
440 }
441 }
442 }
443}
444β
445type QueryObserverMatch = {
446 defaultedQueryOptions: DefaultedQueryObserverOptions
447 observer: QueryObserver
448}