Open History to see the last commit
1'use client'
2
3import { useRef } from 'react'
4import { rejectLiveQueryInput, toBoundaryError } from '@tanstack/db'
5import { useLiveQueryForSuspense } from './useLiveQuery'
6import { getLiveQueryResultInfo } from './live-query-internals'
7import type { UseLiveQueryConfig } from './useLiveQuery'
8import type {
9 Collection,
10 Context,
11 DbClient,
12 GetResult,
13 HealthNode,
14 InferResultType,
15 InitialQueryBuilder,
16 NonSingleResult,
17 QueryBuilder,
18 SingleResult,
19} from '@tanstack/db'
20
21// React can discard a render that suspends, including its refs. Keep the
22// initial-render failure across retries, scoped by client because streamed
23// preloads of the same collection can fail independently.
24const initialRenderErrors = new WeakMap<
25 Collection<any, any, any>,
26 {
27 byClient: WeakMap<DbClient, { error: unknown; clientQuery?: object }>
28 unscoped?: { error: unknown; clientQuery?: object }
29 }
30>()
31
32function clearInitialRenderError(
33 collection: Collection<any, any, any>,
34 client: DbClient | undefined,
35) {
36 const entry = initialRenderErrors.get(collection)
37 if (!entry) return
38 if (client) entry.byClient.delete(client)
39 else delete entry.unscoped
40}
41
42function rememberInitialRenderError(
43 collection: Collection<any, any, any>,
44 client: DbClient | undefined,
45 error: unknown,
46 clientQuery?: object,
47) {
48 if (collection.status === `cleaned-up`) return
49 let entry = initialRenderErrors.get(collection)
50 if (!entry) {
51 entry = { byClient: new WeakMap() }
52 collection.once(`status:cleaned-up`, () => {
53 initialRenderErrors.delete(collection)
54 })
55 initialRenderErrors.set(collection, entry)
56 }
57 if (client) entry.byClient.set(client, { error, clientQuery })
58 else entry.unscoped = { error }
59}
60
61/**
62 * Create a live query with React Suspense support
63 * @param queryFn - Query function that defines what data to fetch
64 * @returns Object with reactive data and state - data is guaranteed to be defined
65 * @throws Promise when data is loading (caught by Suspense boundary)
66 * @throws Error when the first load fails or the Collection crashes (caught by
67 * an Error boundary): the cause itself when it is an Error, otherwise an Error
68 * with the problem's message (`health.error.message`) whose `cause` is the
69 * value the sync adapter reported
70 * @example
71 * // Basic usage with Suspense
72 * function TodoList() {
73 * const { data } = useLiveSuspenseQuery({
74 * query: (q) =>
75 * q.from({ todos: todosCollection })
76 * .where(({ todos }) => eq(todos.completed, false))
77 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
78 * })
79 *
80 * return (
81 * <ul>
82 * {data.map(todo => <li key={todo.id}>{todo.text}</li>)}
83 * </ul>
84 * )
85 * }
86 *
87 * function App() {
88 * return (
89 * <Suspense fallback={<div>Loading...</div>}>
90 * <TodoList />
91 * </Suspense>
92 * )
93 * }
94 *
95 * @example
96 * // Single result query
97 * const { data } = useLiveSuspenseQuery(
98 * (q) => q.from({ todos: todosCollection })
99 * .where(({ todos }) => eq(todos.id, 1))
100 * .findOne()
101 * )
102 * // data is guaranteed to be the single item (or undefined if not found)
103 *
104 * @example
105 * // Structured captured values are included in derived query identity and trigger re-suspension
106 * const { data } = useLiveSuspenseQuery({
107 * query: (q) => q.from({ todos: todosCollection })
108 * .where(({ todos }) => gt(todos.priority, minPriority)),
109 * })
110 *
111 * @example
112 * // With Error boundary
113 * function App() {
114 * return (
115 * <ErrorBoundary fallback={<div>Error loading data</div>}>
116 * <Suspense fallback={<div>Loading...</div>}>
117 * <TodoList />
118 * </Suspense>
119 * </ErrorBoundary>
120 * )
121 * }
122 *
123 * @remarks
124 * **Important:** This hook does NOT support disabled queries (returning undefined/null).
125 * Following TanStack Query's useSuspenseQuery design, the query callback must always
126 * return a valid query, collection, or config object.
127 *
128 * ❌ **This will cause a type error:**
129 * ```ts
130 * useLiveSuspenseQuery(
131 * (q) => userId ? q.from({ users }) : undefined // ❌ Error!
132 * )
133 * ```
134 *
135 * ✅ **Use conditional rendering instead:**
136 * ```ts
137 * function Profile({ userId }: { userId: string }) {
138 * const { data } = useLiveSuspenseQuery({
139 * query: (q) => q.from({ users }).where(({ users }) => eq(users.id, userId)),
140 * })
141 * return <div>{data.name}</div>
142 * }
143 *
144 * // In parent component:
145 * {userId ? <Profile userId={userId} /> : <div>No user</div>}
146 * ```
147 *
148 * ✅ **For optional inputs, conditionally render a component with complete query inputs:**
149 * ```ts
150 * {userId ? <Profile userId={userId} /> : <div>No user</div>}
151 * ```
152 */
153// Overload 1: Accept query function that always returns QueryBuilder
154export function useLiveSuspenseQuery<TContext extends Context>(
155 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
156): {
157 state: Map<string | number, GetResult<TContext>>
158 data: InferResultType<TContext>
159 collection: Collection<GetResult<TContext>, string | number, {}>
160 health: HealthNode | undefined
161}
162
163// Overload 2: Accept config object
164export function useLiveSuspenseQuery<TContext extends Context>(
165 config: UseLiveQueryConfig<TContext>,
166): {
167 state: Map<string | number, GetResult<TContext>>
168 data: InferResultType<TContext>
169 collection: Collection<GetResult<TContext>, string | number, {}>
170 health: HealthNode | undefined
171}
172
173// Overload 4: Accept pre-created live query collection
174export function useLiveSuspenseQuery<
175 TResult extends object,
176 TKey extends string | number,
177 TUtils extends Record<string, any>,
178>(
179 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
180): {
181 state: Map<TKey, TResult>
182 data: Array<TResult>
183 collection: Collection<TResult, TKey, TUtils>
184 health: HealthNode | undefined
185}
186
187// Overload 5: Accept pre-created live query collection with singleResult: true
188export function useLiveSuspenseQuery<
189 TResult extends object,
190 TKey extends string | number,
191 TUtils extends Record<string, any>,
192>(
193 liveQueryCollection: Collection<TResult, TKey, TUtils> & SingleResult,
194): {
195 state: Map<TKey, TResult>
196 data: TResult | undefined
197 collection: Collection<TResult, TKey, TUtils> & SingleResult
198 health: HealthNode | undefined
199}
200
201// Implementation - uses useLiveQuery internally and adds Suspense logic
202export function useLiveSuspenseQuery(configOrQueryOrCollection: any) {
203 const promiseRef = useRef<Promise<void> | null>(null)
204 const collectionRef = useRef<Collection<any, any, any> | null>(null)
205 const hasBeenReadyRef = useRef(false)
206
207 // Use useLiveQuery to handle collection management and reactivity
208 const result = useLiveQueryForSuspense(configOrQueryOrCollection)
209
210 if (!result.isEnabled) {
211 // Suspense queries cannot be disabled - this matches TanStack Query's useSuspenseQuery behavior
212 throw new Error(
213 `useLiveSuspenseQuery does not support disabled queries (callback returned undefined/null). ` +
214 `The Suspense pattern requires data to always be defined (T, not T | undefined). ` +
215 `Solutions: ` +
216 `1) Use conditional rendering - don't render the component until the condition is met. ` +
217 `2) Use useLiveQuery instead, which supports disabled queries with the 'isEnabled' flag.`,
218 )
219 }
220
221 const queryInfo = getLiveQueryResultInfo(result)
222 // The render boundary: an error thrown before this render commits releases
223 // the sync starts it deferred. A thrown promise suspends; its preload owns
224 // those starts.
225 try {
226 // Reset promise and ready state when query identity changes
227 if (collectionRef.current !== result.collection) {
228 promiseRef.current = null
229 collectionRef.current = result.collection
230 hasBeenReadyRef.current = false
231 }
232
233 // SUSPENSE LOGIC: Throw promise or error based on collection status
234
235 const collectionStatus = result.collection.status
236
237 // Track when we reach ready state
238 if (result.isReady) {
239 hasBeenReadyRef.current = true
240 promiseRef.current = null
241 clearInitialRenderError(result.collection, queryInfo.client)
242 }
243
244 const observerError = queryInfo.observer.getError()
245 // A client request can reject with undefined, which getError() cannot
246 // distinguish from no error. The request status preserves that distinction.
247 const clientQuery =
248 queryInfo.client && queryInfo.queryHash
249 ? queryInfo.client._getLiveQuery(queryInfo.queryHash)
250 : undefined
251 if (
252 !hasBeenReadyRef.current &&
253 (observerError !== undefined || clientQuery?.status === `error`)
254 ) {
255 promiseRef.current = null
256 throw observerError === undefined ? clientQuery?.error : observerError
257 }
258
259 if (queryInfo.client?._isSsrStreamingEnabled() && !queryInfo.queryHash) {
260 const reason = queryInfo.identityError
261 ? `${queryInfo.identityError.reason} at ${queryInfo.identityError.path}`
262 : `the query has no stable identity`
263 throw new Error(
264 `Cannot stream this live query during SSR because ${reason}. Provide an explicit serializable queryKey.`,
265 )
266 }
267 const errorEntry = initialRenderErrors.get(result.collection)
268 const initialRenderError = queryInfo.client
269 ? errorEntry?.byClient.get(queryInfo.client)
270 : errorEntry?.unscoped
271 // A replacement client query must not inherit the prior request's error.
272 if (
273 initialRenderError?.clientQuery !== undefined &&
274 initialRenderError.clientQuery !== clientQuery
275 ) {
276 clearInitialRenderError(result.collection, queryInfo.client)
277 } else if (initialRenderError && !hasBeenReadyRef.current) {
278 promiseRef.current = null
279 throw toBoundaryError(initialRenderError.error)
280 }
281
282 // A failed first load throws only before the first ready; later sync
283 // problems surface in `health` with the data kept (as in TanStack Query).
284 // A crash throws at any time: the Collection can no longer serve reads.
285 if (
286 collectionStatus === `crashed` ||
287 (collectionStatus === `error` && !hasBeenReadyRef.current)
288 ) {
289 promiseRef.current = null
290 throw toBoundaryError(result.collection.health.error?.cause)
291 }
292
293 if (
294 !hasBeenReadyRef.current &&
295 (result.isLoading ||
296 result.isIdle ||
297 result.isLoadingError ||
298 result.isCrashed)
299 ) {
300 // Create or reuse promise for current collection
301 if (!promiseRef.current) {
302 const collection = result.collection
303 const client = queryInfo.client
304 const queryHash = queryInfo.queryHash
305 let active = true
306 const stopWatchingCleanup = collection.once(`status:cleaned-up`, () => {
307 active = false
308 })
309 let preload: Promise<void>
310 try {
311 preload = queryInfo.observer.preload()
312 } catch (error) {
313 stopWatchingCleanup()
314 throw error
315 }
316 const preloadClientQuery =
317 client && queryHash ? client._getLiveQuery(queryHash) : undefined
318 promiseRef.current = preload
319 .catch((error: unknown) => {
320 const latestClientQuery =
321 client && queryHash ? client._getLiveQuery(queryHash) : undefined
322 if (active && latestClientQuery === preloadClientQuery)
323 rememberInitialRenderError(
324 collection,
325 client,
326 error,
327 preloadClientQuery,
328 )
329 throw error
330 })
331 .finally(stopWatchingCleanup)
332 }
333 // React Suspense catches this promise and retries after preload settles.
334 throw promiseRef.current
335 }
336
337 // Return data without status/loading flags (handled by Suspense/ErrorBoundary)
338 // If error after success, return last known good state (stale data)
339 return {
340 state: result.state,
341 data: result.data,
342 collection: result.collection,
343 health: result.health,
344 }
345 } catch (error) {
346 if (error instanceof Promise) throw error
347 return rejectLiveQueryInput(queryInfo.deferredCollections, error)
348 }
349}