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

useLiveSuspenseQuery.ts

248 lines8.2 KB

1'use client'
2​
3import { useRef } from 'react'
4import { useLiveQueryForSuspense } from './useLiveQuery'
5import { getLiveQueryResultInfo } from './live-query-internals'
6import type { UseLiveQueryConfig } from './useLiveQuery'
7import type {
8 Collection,
9 Context,
10 GetResult,
11 InferResultType,
12 InitialQueryBuilder,
13 LiveQueryCollectionConfig,
14 NonSingleResult,
15 QueryBuilder,
16 SingleResult,
17} from '@tanstack/db'
18​
19/**
20 * Create a live query with React Suspense support
21 * @param queryFn - Query function that defines what data to fetch
22 * @param deps - Deprecated array of dependencies that trigger query re-execution when changed
23 * @returns Object with reactive data and state - data is guaranteed to be defined
24 * @throws Promise when data is loading (caught by Suspense boundary)
25 * @throws Error when collection fails (caught by Error boundary)
26 * @example
27 * // Basic usage with Suspense
28 * function TodoList() {
29 * const { data } = useLiveSuspenseQuery({
30 * query: (q) =>
31 * q.from({ todos: todosCollection })
32 * .where(({ todos }) => eq(todos.completed, false))
33 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
34 * })
35 *
36 * return (
37 * <ul>
38 * {data.map(todo => <li key={todo.id}>{todo.text}</li>)}
39 * </ul>
40 * )
41 * }
42 *
43 * function App() {
44 * return (
45 * <Suspense fallback={<div>Loading...</div>}>
46 * <TodoList />
47 * </Suspense>
48 * )
49 * }
50 *
51 * @example
52 * // Single result query
53 * const { data } = useLiveSuspenseQuery(
54 * (q) => q.from({ todos: todosCollection })
55 * .where(({ todos }) => eq(todos.id, 1))
56 * .findOne()
57 * )
58 * // data is guaranteed to be the single item (or undefined if not found)
59 *
60 * @example
61 * // Structured captured values are included in derived query identity and trigger re-suspension
62 * const { data } = useLiveSuspenseQuery({
63 * query: (q) => q.from({ todos: todosCollection })
64 * .where(({ todos }) => gt(todos.priority, minPriority)),
65 * })
66 *
67 * @example
68 * // With Error boundary
69 * function App() {
70 * return (
71 * <ErrorBoundary fallback={<div>Error loading data</div>}>
72 * <Suspense fallback={<div>Loading...</div>}>
73 * <TodoList />
74 * </Suspense>
75 * </ErrorBoundary>
76 * )
77 * }
78 *
79 * @remarks
80 * **Important:** This hook does NOT support disabled queries (returning undefined/null).
81 * Following TanStack Query's useSuspenseQuery design, the query callback must always
82 * return a valid query, collection, or config object.
83 *
84 * ❌ **This will cause a type error:**
85 * ```ts
86 * useLiveSuspenseQuery(
87 * (q) => userId ? q.from({ users }) : undefined // ❌ Error!
88 * )
89 * ```
90 *
91 * ✅ **Use conditional rendering instead:**
92 * ```ts
93 * function Profile({ userId }: { userId: string }) {
94 * const { data } = useLiveSuspenseQuery({
95 * query: (q) => q.from({ users }).where(({ users }) => eq(users.id, userId)),
96 * })
97 * return <div>{data.name}</div>
98 * }
99 *
100 * // In parent component:
101 * {userId ? <Profile userId={userId} /> : <div>No user</div>}
102 * ```
103 *
104 * ✅ **For optional inputs, conditionally render a component with complete query inputs:**
105 * ```ts
106 * {userId ? <Profile userId={userId} /> : <div>No user</div>}
107 * ```
108 */
109// Overload 1: Accept query function that always returns QueryBuilder
110export function useLiveSuspenseQuery<TContext extends Context>(
111 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
112 deps?: Array<unknown>,
113): {
114 state: Map<string | number, GetResult<TContext>>
115 data: InferResultType<TContext>
116 collection: Collection<GetResult<TContext>, string | number, {}>
118​
119// Overload 2: Accept config object
120export function useLiveSuspenseQuery<TContext extends Context>(
121 config: UseLiveQueryConfig<TContext>,
122): {
123 state: Map<string | number, GetResult<TContext>>
124 data: InferResultType<TContext>
125 collection: Collection<GetResult<TContext>, string | number, {}>
127​
128// Overload 3: Accept legacy config object
129export function useLiveSuspenseQuery<TContext extends Context>(
130 config: LiveQueryCollectionConfig<TContext>,
131 deps?: Array<unknown>,
132): {
133 state: Map<string | number, GetResult<TContext>>
134 data: InferResultType<TContext>
135 collection: Collection<GetResult<TContext>, string | number, {}>
137​
138// Overload 4: Accept pre-created live query collection
139export function useLiveSuspenseQuery<
140 TResult extends object,
141 TKey extends string | number,
142 TUtils extends Record<string, any>,
143>(
144 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
145): {
146 state: Map<TKey, TResult>
147 data: Array<TResult>
148 collection: Collection<TResult, TKey, TUtils>
150​
151// Overload 5: Accept pre-created live query collection with singleResult: true
152export function useLiveSuspenseQuery<
153 TResult extends object,
154 TKey extends string | number,
155 TUtils extends Record<string, any>,
156>(
157 liveQueryCollection: Collection<TResult, TKey, TUtils> & SingleResult,
158): {
159 state: Map<TKey, TResult>
160 data: TResult | undefined
161 collection: Collection<TResult, TKey, TUtils> & SingleResult
163​
164// Implementation - uses useLiveQuery internally and adds Suspense logic
165export function useLiveSuspenseQuery(
166 configOrQueryOrCollection: any,
167 deps?: Array<unknown>,
168) {
169 const promiseRef = useRef<Promise<void> | null>(null)
170 const collectionRef = useRef<Collection<any, any, any> | null>(null)
171 const hasBeenReadyRef = useRef(false)
172​
173 // Use useLiveQuery to handle collection management and reactivity
174 const result =
175 deps === undefined
176 ? useLiveQueryForSuspense(configOrQueryOrCollection, undefined)
177 : useLiveQueryForSuspense(configOrQueryOrCollection, deps)
178​
179 if (!result.isEnabled) {
180 // Suspense queries cannot be disabled - this matches TanStack Query's useSuspenseQuery behavior
181 throw new Error(
182 `useLiveSuspenseQuery does not support disabled queries (callback returned undefined/null). ` +
183 `The Suspense pattern requires data to always be defined (T, not T | undefined). ` +
184 `Solutions: ` +
185 `1) Use conditional rendering - don't render the component until the condition is met. ` +
186 `2) Use useLiveQuery instead, which supports disabled queries with the 'isEnabled' flag.`,
187 )
188 }
189​
190 const queryInfo = getLiveQueryResultInfo(result)
191​
192 // Reset promise and ready state when query identity changes
193 if (collectionRef.current !== result.collection) {
194 promiseRef.current = null
195 collectionRef.current = result.collection
196 hasBeenReadyRef.current = false
197 }
198​
199 // SUSPENSE LOGIC: Throw promise or error based on collection status
200​
201 const collectionStatus = result.collection.status
202​
203 // Track when we reach ready state
204 if (result.isReady) {
205 hasBeenReadyRef.current = true
206 promiseRef.current = null
207 }
208​
209 const observerError = queryInfo.observer.getError()
210 if (observerError !== undefined && !hasBeenReadyRef.current) {
211 promiseRef.current = null
212 throw observerError
213 }
214​
215 // Only throw errors during initial load (before first ready)
216 // After success, errors surface as stale data (matches TanStack Query behavior)
217 if (collectionStatus === `error` && !hasBeenReadyRef.current) {
218 promiseRef.current = null
219 // TODO: Once collections hold a reference to their last error object (#671),
220 // we should rethrow that actual error instead of creating a generic message
221 throw new Error(`Collection "${result.collection.id}" failed to load`)
222 }
223​
224 if (!hasBeenReadyRef.current && (result.isLoading || result.isIdle)) {
225 if (queryInfo.client?._isSsrStreamingEnabled() && !queryInfo.queryHash) {
226 const reason = queryInfo.identityError
227 ? `${queryInfo.identityError.reason} at ${queryInfo.identityError.path}`
228 : `the query has no stable identity`
229 throw new Error(
230 `Cannot stream this live query during SSR because ${reason}. Provide an explicit serializable queryKey.`,
231 )
232 }
233 // Create or reuse promise for current collection
234 if (!promiseRef.current) {
235 promiseRef.current = queryInfo.observer.preload()
236 }
237 // React Suspense catches this promise and retries after preload settles.
238 throw promiseRef.current
239 }
240​
241 // Return data without status/loading flags (handled by Suspense/ErrorBoundary)
242 // If error after success, return last known good state (stale data)
243 return {
244 state: result.state,
245 data: result.data,
246 collection: result.collection,
247 }