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

useLiveSuspenseQuery.ts

223 lines7.5 KB

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