Open History to see the last commit
1import { useMemo, useState } from 'react'
2import { useLiveQuery } from './useLiveQuery'
3import type {
4 Collection,
5 Context,
6 GetResult,
7 InferResultType,
8 InitialQueryBuilder,
9 LiveQueryCollectionConfig,
10 NonSingleResult,
11 QueryBuilder,
12 SingleResult,
13} from '@tanstack/db'
14
15const safePromiseCache = new WeakMap<Promise<void>, Promise<void>>()
16
17/**
18 * Create a live query with React Suspense support
19 * @param queryFn - Query function that defines what data to fetch
20 * @param deps - Array of dependencies that trigger query re-execution when changed
21 * @returns Object with reactive data and state - data is guaranteed to be defined
22 * @throws Promise when data is loading (caught by Suspense boundary)
23 * @throws Error when collection fails (caught by Error boundary)
24 * @example
25 * // Basic usage with Suspense
26 * function TodoList() {
27 * const { data } = useLiveSuspenseQuery((q) =>
28 * q.from({ todos: todosCollection })
29 * .where(({ todos }) => eq(todos.completed, false))
30 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
31 * )
32 *
33 * return (
34 * <ul>
35 * {data.map(todo => <li key={todo.id}>{todo.text}</li>)}
36 * </ul>
37 * )
38 * }
39 *
40 * function App() {
41 * return (
42 * <Suspense fallback={<div>Loading...</div>}>
43 * <TodoList />
44 * </Suspense>
45 * )
46 * }
47 *
48 * @example
49 * // Single result query
50 * const { data } = useLiveSuspenseQuery(
51 * (q) => q.from({ todos: todosCollection })
52 * .where(({ todos }) => eq(todos.id, 1))
53 * .findOne()
54 * )
55 * // data is guaranteed to be the single item (or undefined if not found)
56 *
57 * @example
58 * // With dependencies that trigger re-suspension
59 * const { data } = useLiveSuspenseQuery(
60 * (q) => q.from({ todos: todosCollection })
61 * .where(({ todos }) => gt(todos.priority, minPriority)),
62 * [minPriority] // Re-suspends when minPriority changes
63 * )
64 *
65 * @example
66 * // With Error boundary
67 * function App() {
68 * return (
69 * <ErrorBoundary fallback={<div>Error loading data</div>}>
70 * <Suspense fallback={<div>Loading...</div>}>
71 * <TodoList />
72 * </Suspense>
73 * </ErrorBoundary>
74 * )
75 * }
76 *
77 * @remarks
78 * **Important:** This hook does NOT support disabled queries (returning undefined/null).
79 * Following TanStack Query's useSuspenseQuery design, the query callback must always
80 * return a valid query, collection, or config object.
81 *
82 * ❌ **This will cause a type error:**
83 * ```ts
84 * useLiveSuspenseQuery(
85 * (q) => userId ? q.from({ users }) : undefined // ❌ Error!
86 * )
87 * ```
88 *
89 * ✅ **Use conditional rendering instead:**
90 * ```ts
91 * function Profile({ userId }: { userId: string }) {
92 * const { data } = useLiveSuspenseQuery(
93 * (q) => q.from({ users }).where(({ users }) => eq(users.id, userId))
94 * )
95 * return <div>{data.name}</div>
96 * }
97 *
98 * // In parent component:
99 * {userId ? <Profile userId={userId} /> : <div>No user</div>}
100 * ```
101 *
102 * ✅ **Or use useLiveQuery for conditional queries:**
103 * ```ts
104 * const { data, isEnabled } = useLiveQuery(
105 * (q) => userId ? q.from({ users }) : undefined, // ✅ Supported!
106 * [userId]
107 * )
108 * ```
109 */
110// Overload 1: Accept query function that always returns QueryBuilder
111export function useLiveSuspenseQuery<TContext extends Context>(
112 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
113 deps?: Array<unknown>,
114): {
115 state: Map<string | number, GetResult<TContext>>
116 data: InferResultType<TContext>
117 collection: Collection<GetResult<TContext>, string | number, {}>
118}
119
120// Overload 2: Accept config object
121export function useLiveSuspenseQuery<TContext extends Context>(
122 config: LiveQueryCollectionConfig<TContext>,
123 deps?: Array<unknown>,
124): {
125 state: Map<string | number, GetResult<TContext>>
126 data: InferResultType<TContext>
127 collection: Collection<GetResult<TContext>, string | number, {}>
128}
129
130// Overload 3: Accept pre-created live query collection
131export function useLiveSuspenseQuery<
132 TResult extends object,
133 TKey extends string | number,
134 TUtils extends Record<string, any>,
135>(
136 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
137): {
138 state: Map<TKey, TResult>
139 data: Array<TResult>
140 collection: Collection<TResult, TKey, TUtils>
141}
142
143// Overload 4: Accept pre-created live query collection with singleResult: true
144export function useLiveSuspenseQuery<
145 TResult extends object,
146 TKey extends string | number,
147 TUtils extends Record<string, any>,
148>(
149 liveQueryCollection: Collection<TResult, TKey, TUtils> & SingleResult,
150): {
151 state: Map<TKey, TResult>
152 data: TResult | undefined
153 collection: Collection<TResult, TKey, TUtils> & SingleResult
154}
155
156// Implementation - uses useLiveQuery internally and adds Suspense logic
157export function useLiveSuspenseQuery(
158 configOrQueryOrCollection: any,
159 deps: Array<unknown> = [],
160) {
161 // Use useLiveQuery to handle collection management and reactivity
162 const result = useLiveQuery(configOrQueryOrCollection, deps)
163
164 const [prevCollection, setPrevCollection] = useState(result.collection)
165 const [hasBeenReady, setHasBeenReady] = useState(false)
166
167 // Reset promise and ready state when collection changes (deps changed)
168 if (prevCollection !== result.collection) {
169 setPrevCollection(result.collection)
170 setHasBeenReady(false)
171 }
172
173 // SUSPENSE LOGIC: Throw promise or error based on collection status
174 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
175 if (!result.isEnabled) {
176 // Suspense queries cannot be disabled - this matches TanStack Query's useSuspenseQuery behavior
177 throw new Error(
178 `useLiveSuspenseQuery does not support disabled queries (callback returned undefined/null). ` +
179 `The Suspense pattern requires data to always be defined (T, not T | undefined). ` +
180 `Solutions: ` +
181 `1) Use conditional rendering - don't render the component until the condition is met. ` +
182 `2) Use useLiveQuery instead, which supports disabled queries with the 'isEnabled' flag.`,
183 )
184 }
185
186 // It’s not recommended to suspend a render based on a store value returned by useSyncExternalStore.
187 // result.status is the snapshot from syncExternalStore. We read the fresh status from the collection reference instead.
188 const collectionStatus = result.collection.status
189
190 // Track when we reach ready state
191 if (collectionStatus === `ready` && !hasBeenReady) {
192 setHasBeenReady(true)
193 }
194
195 // Only throw errors during initial load (before first ready)
196 // After success, errors surface as stale data (matches TanStack Query behavior)
197 if (collectionStatus === `error` && !hasBeenReady) {
198 // TODO: Once collections hold a reference to their last error object (#671),
199 // we should rethrow that actual error instead of creating a generic message
200 throw new Error(`Collection "${result.collection.id}" failed to load`)
201 }
202
203 if (collectionStatus === `loading` || collectionStatus === `idle`) {
204 // Create or reuse promise for current collection
205 const promise = result.collection.preload()
206 let safePromise = safePromiseCache.get(promise)
207 if (!safePromise) {
208 safePromise = promise.catch(() => {})
209 safePromiseCache.set(promise, safePromise)
210 }
211 // THROW PROMISE - React Suspense catches this (React 18+ required)
212 // Note: We don't check React version here. In React <18, this will be caught
213 // by an Error Boundary, which provides a reasonable failure mode.
214 throw safePromise
215 }
216
217 // Return data without status/loading flags (handled by Suspense/ErrorBoundary)
218 // If error after success, return last known good state (stale data)
219 return useMemo(
220 () => ({
221 state: result.state,
222 data: result.data,
223 collection: result.collection,
224 }),
225 [result.collection, result.data, result.state],
226 )
227}