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 { QueryClient } from './queryClient'
6import type {
7 DefaultedQueryObserverOptions,
8 QueryObserverOptions,
9 QueryObserverResult,
10} from './types'
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) => this.#subscribeTo(observer))
97 }
98 }
99β
100 protected override onUnsubscribe(): void {
101 if (!this.listeners.size) {
102 this.destroy()
103 }
104 }
105β
106 /**
107 * Stops observing all queries: clears all listeners and destroys every
108 * underlying `QueryObserver` this observer manages.
109 */
110 destroy(): void {
111 this.listeners = new Set()
112 this.#observers.forEach((observer) => {
113 observer.destroy()
114 })
115 }
116β
117 /**
118 * Replaces the set of queries being observed. Existing `QueryObserver`s
119 * are reused for queries that match an already-observed query hash;
120 * observers for queries that are no longer present are destroyed, and new
121 * observers are created and subscribed to for newly added queries.
122 * @param queries - The options of the queries to observe.
123 * @param options - Replaces the observer's options, e.g. its `combine` function.
124 * @example
125 * ```ts
126 * observer.setQueries([
127 * { queryKey: ['post', 1], queryFn: fetchPost },
128 * { queryKey: ['post', 3], queryFn: fetchPost },
129 * ])
130 * ```
131 */
132 setQueries(
133 queries: Array<QueryObserverOptions>,
134 options?: QueriesObserverOptions<TCombinedResult>,
135 ): void {
136 this.#queries = queries
137 this.#options = options
138β
139 if (process.env.NODE_ENV !== 'production') {
140 const queryHashes = queries.map(
141 (query) => this.#client.defaultQueryOptions(query).queryHash,
142 )
143 if (new Set(queryHashes).size !== queryHashes.length) {
144 console.warn(
145 '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.',
146 )
147 }
148 }
149β
150 notifyManager.batch(() => {
151 const prevObservers = this.#observers
152β
153 const newObserverMatches = this.#findMatchingObservers(this.#queries)
154β
155 // set options for the new observers to notify of changes
156 newObserverMatches.forEach((match) =>
157 match.observer.setOptions(match.defaultedQueryOptions),
158 )
159β
160 const newObservers = newObserverMatches.map((match) => match.observer)
161 const newResult = newObservers.map((observer) =>
162 observer.getCurrentResult(),
163 )
164β
165 const hasLengthChange = prevObservers.length !== newObservers.length
166 const hasIndexChange = newObservers.some(
167 (observer, index) => observer !== prevObservers[index],
168 )
169 const hasStructuralChange = hasLengthChange || hasIndexChange
170β
171 const hasResultChange = hasStructuralChange
172 ? true
173 : newResult.some((result, index) => {
174 const prev = this.#result[index]
175 return !prev || !shallowEqualObjects(result, prev)
176 })
177β
178 if (!hasStructuralChange && !hasResultChange) return
179β
180 if (hasStructuralChange) {
181 this.#observerMatches = newObserverMatches
182 this.#observers = newObservers
183 }
184β
185 this.#result = newResult
186β
187 if (!this.hasListeners()) return
188β
189 if (hasStructuralChange) {
190 difference(prevObservers, newObservers).forEach((observer) => {
191 observer.destroy()
192 })
193 difference(newObservers, prevObservers).forEach((observer) =>
194 this.#subscribeTo(observer),
195 )
196 }
197β
198 this.#notify()
199 })
200 }
201β
202 /**
203 * Returns the most recently computed array of `QueryObserverResult`s, one
204 * per observed query, in the same order as the queries passed to the
205 * constructor or `setQueries`.
206 * @returns The current results.
207 * @example
208 * ```ts
209 * const results = observer.getCurrentResult()
210 * const data = results.map((result) => result.data)
211 * ```
212 */
213 getCurrentResult(): Array<QueryObserverResult> {
214 return this.#result
215 }
216β
217 /**
218 * Returns the underlying `Query` instances currently being observed, in
219 * the same order as the queries passed to the constructor or `setQueries`.
220 * @returns The observed queries.
221 */
222 getQueries() {
223 return this.#observers.map((observer) => observer.getCurrentQuery())
224 }
225β
226 /**
227 * Returns the underlying `QueryObserver` instances this observer manages,
228 * in the same order as the queries passed to the constructor or
229 * `setQueries`.
230 * @returns The managed query observers.
231 */
232 getObservers() {
233 return this.#observers
234 }
235β
236 /**
237 * The `QueriesObserver` counterpart of {@link QueryObserver#getOptimisticResult} β computes
238 * the result for the given (already-defaulted) queries right now, synchronously. Called by
239 * framework adapters (e.g. `useQueries`) ahead of subscribing, returning a tuple of the raw
240 * per-query results, a function to compute the combined result from them, and a function to
241 * wrap the results for property-access tracking. When the queries match the observed ones, the
242 * results also become the current result, so a later `setQueries` call with the same queries
243 * does not notify the listeners about them.
244 * @param queries - The defaulted options of the queries to compute the result for.
245 * @param combine - The `combine` function used by the returned `combineResult`, if any.
246 * @returns A tuple of the per-query results, a function that computes the combined result, and a
247 * function that returns the results wrapped for property-access tracking.
248 */
249 getOptimisticResult(
250 queries: Array<QueryObserverOptions>,
251 combine: CombineFn<TCombinedResult> | undefined,
252 ): [
253 rawResult: Array<QueryObserverResult>,
254 combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult,
255 trackResult: () => Array<QueryObserverResult>,
256 ] {
257 const matches = this.#findMatchingObservers(queries)
258 const result = matches.map((match) =>
259 match.observer.getOptimisticResult(match.defaultedQueryOptions),
260 )
261 // The observers now hold the optimistic results as their current results.
262 // Hold them here too, so that `setQueries` does not find a change (and
263 // notify) for results that the caller already has.
264 if (
265 matches.length === this.#observers.length &&
266 matches.some(
267 (match, index) =>
268 match.observer.getCurrentResult() !== this.#result[index],
269 ) &&
270 matches.every((match, index) => match.observer === this.#observers[index])
271 ) {
272 this.#result = matches.map((match) => match.observer.getCurrentResult())
273 }
274 const queryHashes = matches.map(
275 (match) => match.defaultedQueryOptions.queryHash,
276 )
277β
278 return [
279 result,
280 (r?: Array<QueryObserverResult>) => {
281 return this.#combineResult(r ?? result, combine, queryHashes)
282 },
283 () => {
284 return this.#trackResult(result, matches)
285 },
286 ]
287 }
288β
289 #trackResult(
290 result: Array<QueryObserverResult>,
291 matches: Array<QueryObserverMatch>,
292 ) {
293 const trackedProps = new Set<keyof QueryObserverResult>()
294β
295 return matches.map((match, index) => {
296 const observerResult = result[index]!
297 return !match.defaultedQueryOptions.notifyOnChangeProps
298 ? match.observer.trackResult(observerResult, (accessedProp) => {
299 // track property on all observers to ensure proper (synchronized) tracking (#7000)
300 if (!trackedProps.has(accessedProp)) {
301 trackedProps.add(accessedProp)
302 matches.forEach((m) => {
303 m.observer.trackProp(accessedProp)
304 })
305 }
306 })
307 : observerResult
308 })
309 }
310β
311 #combineResult(
312 input: Array<QueryObserverResult>,
313 combine: CombineFn<TCombinedResult> | undefined,
314 queryHashes?: Array<string>,
315 ): TCombinedResult {
316 if (combine) {
317 const lastHashes = this.#lastQueryHashes
318 const queryHashesChanged =
319 queryHashes !== undefined &&
320 lastHashes !== undefined &&
321 (lastHashes.length !== queryHashes.length ||
322 queryHashes.some((hash, i) => hash !== lastHashes[i]))
323β
324 if (
325 this.#result !== this.#lastResult ||
326 queryHashesChanged ||
327 combine !== this.#lastCombine
328 ) {
329 this.#lastCombine = combine
330 this.#lastResult = this.#result
331β
332 if (queryHashes !== undefined) {
333 this.#lastQueryHashes = queryHashes
334 }
335 this.#combinedResult = replaceEqualDeep(
336 this.#combinedResult,
337 combine(input),
338 )
339 }
340β
341 return this.#combinedResult
342 }
343 return input as any
344 }
345β
346 #shouldSkipCombine(): boolean {
347 return (
348 !this.#options?.combine ||
349 this.#observers.some((observer, index) => {
350 return (
351 observer.options.suspense && this.#result[index]?.data === undefined
352 )
353 })
354 )
355 }
356β
357 #findMatchingObservers(
358 queries: Array<QueryObserverOptions>,
359 ): Array<QueryObserverMatch> {
360 const prevObserversMap = new Map<string, Array<QueryObserver>>()
361β
362 this.#observers.forEach((observer) => {
363 const key = observer.options.queryHash
364 if (!key) return
365β
366 const previousObservers = prevObserversMap.get(key)
367β
368 if (previousObservers) {
369 previousObservers.push(observer)
370 } else {
371 prevObserversMap.set(key, [observer])
372 }
373 })
374β
375 const observers: Array<QueryObserverMatch> = []
376β
377 queries.forEach((options) => {
378 const defaultedOptions = this.#client.defaultQueryOptions(options)
379 const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift()
380 const observer =
381 match ?? new QueryObserver(this.#client, defaultedOptions)
382β
383 observers.push({
384 defaultedQueryOptions: defaultedOptions,
385 observer,
386 })
387 })
388β
389 return observers
390 }
391β
392 #subscribeTo(observer: QueryObserver): void {
393 // Create the listener here, not in `setQueries`: a listener created there
394 // keeps the previous observers, and their queries, alive (#12656)
395 observer.subscribe((result) => {
396 this.#onUpdate(observer, result)
397 })
398 }
399β
400 #onUpdate(observer: QueryObserver, result: QueryObserverResult): void {
401 const index = this.#observers.indexOf(observer)
402 if (index !== -1) {
403 this.#result = this.#result.slice()
404 this.#result[index] = result
405 this.#notify()
406 }
407 }
408β
409 #notify(): void {
410 if (this.hasListeners()) {
411 const shouldSkipCombine = this.#shouldSkipCombine()
412 const previousResult = this.#combinedResult
413 const newResult = shouldSkipCombine
414 ? previousResult
415 : this.#combineResult(
416 this.#trackResult(this.#result, this.#observerMatches),
417 this.#options?.combine,
418 this.#observerMatches.map(
419 (match) => match.defaultedQueryOptions.queryHash,
420 ),
421 )
422β
423 if (shouldSkipCombine || previousResult !== newResult) {
424 notifyManager.batch(() => {
425 this.listeners.forEach((listener) => {
426 listener(this.#result)
427 })
428 })
429 }
430 }
431 }
432}
433β
434type QueryObserverMatch = {
435 defaultedQueryOptions: DefaultedQueryObserverOptions
436 observer: QueryObserver
437}