Open History to see the last commit
1import {
2 QueriesObserver,
3 QueryObserver,
4 noop,
5 notifyManager,
6} from '@tanstack/query-core'
7import {
8 useCallback,
9 useEffect,
10 useMemo,
11 useState,
12 useSyncExternalStore,
13} from 'octane'
14import { resolveClient } from './context'
15import { useIsRestoring } from './isRestoring'
16import { useQueryErrorResetBoundary } from './errorResetBoundary'
17import {
18 ensurePreventErrorBoundaryRetry,
19 ensureSuspenseTimers,
20 fetchOptimistic,
21 getHasError,
22 shouldSuspend,
23 splitSlot,
24 subSlot,
25 useSuspensePromise,
26} from './internal'
27import type { QueryClient } from '@tanstack/query-core'
28import type {
29 GetUseQueryOptionsForUseQueries,
30 QueriesOptions,
31 QueriesResults,
32} from './queries-types'
33
34// Signature matches @tanstack/react-query's useQueries.ts — per-entry tuple
35// inference via QueriesOptions/QueriesResults, with `combine` re-typing the
36// aggregate result. The untyped implementation signature also accepts the
37// compiler-injected trailing slot symbol.
38export function useQueries<
39 T extends Array<any>,
40 TCombinedResult = QueriesResults<T>,
41>(
42 options: {
43 queries:
44 | readonly [...QueriesOptions<T>]
45 | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> }]
46 combine?: (result: QueriesResults<T>) => TCombinedResult
47 subscribed?: boolean
48 },
49 queryClient?: QueryClient,
50): TCombinedResult
51
52export function useQueries(options: any, ...rest: Array<any>): any {
53 const [user, slot] = splitSlot(rest)
54 const client = resolveClient(user[0])
55 const isRestoring = useIsRestoring()
56 const errorResetBoundary = useQueryErrorResetBoundary()
57 const { queries, ...restOptions } = options
58 const qs = (tag: string) => subSlot(slot, 'qs:' + tag)
59
60 const defaultedQueries = useMemo(
61 () =>
62 queries.map((opts: any) => {
63 const defaulted = client.defaultQueryOptions(opts)
64 defaulted._optimisticResults = isRestoring
65 ? 'isRestoring'
66 : 'optimistic'
67 return defaulted
68 }),
69 [queries, client, isRestoring],
70 qs('memo'),
71 )
72 defaultedQueries.forEach((queryOptions: any) => {
73 ensureSuspenseTimers(queryOptions)
74 ensurePreventErrorBoundaryRetry(
75 queryOptions,
76 errorResetBoundary,
77 client.getQueryCache().get(queryOptions.queryHash),
78 )
79 })
80 useEffect(
81 () => {
82 errorResetBoundary.clearReset()
83 },
84 [errorResetBoundary],
85 qs('clr'),
86 )
87
88 const [observer] = useState(
89 () => new QueriesObserver(client, defaultedQueries, restOptions),
90 qs('obs'),
91 )
92
93 const [optimisticResult, getCombinedResult, trackResult] =
94 observer.getOptimisticResult(defaultedQueries, restOptions.combine)
95
96 const shouldSubscribe = !isRestoring && restOptions.subscribed !== false
97 useSyncExternalStore(
98 useCallback(
99 (onStoreChange: () => void) =>
100 shouldSubscribe
101 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
102 : noop,
103 [observer, shouldSubscribe],
104 qs('cb'),
105 ),
106 () => observer.getCurrentResult(),
107 () => observer.getCurrentResult(),
108 qs('uses'),
109 )
110
111 useEffect(
112 () => {
113 observer.setQueries(defaultedQueries, restOptions)
114 },
115 [defaultedQueries, restOptions, observer],
116 qs('eff'),
117 )
118
119 // If any query should suspend, await their optimistic fetches as one retained
120 // suspense promise. Retaining it gives a sequential useQueries call the same
121 // stable replay position as useBaseQuery above.
122 const suspenseIndexes: Array<number> = []
123 for (let index = 0; index < optimisticResult.length; index++) {
124 if (shouldSuspend(defaultedQueries[index], optimisticResult[index])) {
125 suspenseIndexes.push(index)
126 }
127 }
128 useSuspensePromise(
129 suspenseIndexes.length > 0,
130 JSON.stringify(
131 suspenseIndexes.map((index) => defaultedQueries[index].queryHash),
132 ),
133 () =>
134 Promise.all(
135 suspenseIndexes.map((index) => {
136 const opts = defaultedQueries[index]
137 // fetchOptimistic clears the reset boundary on error (upstream
138 // suspense.ts) so a reset→retry→fail-again re-throws to the boundary.
139 return fetchOptimistic(
140 opts,
141 new QueryObserver(client, opts),
142 errorResetBoundary,
143 )
144 }),
145 ),
146 qs('sus'),
147 )
148
149 const firstError = optimisticResult.find((result: any, index: number) => {
150 const query = defaultedQueries[index]
151 return (
152 query &&
153 getHasError({
154 result,
155 errorResetBoundary,
156 throwOnError: query.throwOnError,
157 query: client.getQueryCache().get(query.queryHash),
158 suspense: query.suspense,
159 })
160 )
161 })
162 if (firstError?.error) {
163 throw firstError.error
164 }
165
166 return getCombinedResult(trackResult())
167}