Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

useLiveSuspenseQuery.ts

369 lines12.4 KB

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