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

useLiveSuspenseQuery.ts

352 lines11.5 KB

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