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