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