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

useLiveQuery.ts

454 lines15.3 KB

1import { useCallback, useState, useSyncExternalStore } from 'react'
2import {
3 BaseQueryBuilder,
4 createLiveQueryCollection,
5 createLiveQueryObserver,
6 isCollection,
7} from '@tanstack/db'
8import type {
9 Collection,
10 CollectionStatus,
11 Context,
12 GetResult,
13 InferResultType,
14 InitialQueryBuilder,
15 LiveQueryCollectionConfig,
16 NonSingleResult,
17 QueryBuilder,
18 SingleResult,
19} from '@tanstack/db'
20​
21const DEFAULT_GC_TIME_MS = 1 // Live queries created by useLiveQuery are cleaned up immediately (0 disables GC)
22​
23export type UseLiveQueryStatus = CollectionStatus | `disabled`
24​
25/**
26 * Create a live query using a query function
27 * @param queryFn - Query function that defines what data to fetch
28 * @param deps - Array of dependencies that trigger query re-execution when changed
29 * @returns Object with reactive data, state, and status information
30 * @example
31 * // Basic query with object syntax
32 * const { data, isLoading } = useLiveQuery((q) =>
33 * q.from({ todos: todosCollection })
34 * .where(({ todos }) => eq(todos.completed, false))
35 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
36 * )
37 *
38 * @example
39 * // Single result query
40 * const { data } = useLiveQuery(
41 * (q) => q.from({ todos: todosCollection })
42 * .where(({ todos }) => eq(todos.id, 1))
43 * .findOne()
44 * )
45 *
46 * @example
47 * // With dependencies that trigger re-execution
48 * const { data, state } = useLiveQuery(
49 * (q) => q.from({ todos: todosCollection })
50 * .where(({ todos }) => gt(todos.priority, minPriority)),
51 * [minPriority] // Re-run when minPriority changes
52 * )
53 *
54 * @example
55 * // Join pattern
56 * const { data } = useLiveQuery((q) =>
57 * q.from({ issues: issueCollection })
58 * .join({ persons: personCollection }, ({ issues, persons }) =>
59 * eq(issues.userId, persons.id)
60 * )
61 * .select(({ issues, persons }) => ({
62 * id: issues.id,
63 * title: issues.title,
64 * userName: persons.name
65 * }))
66 * )
67 *
68 * @example
69 * // Handle loading and error states
70 * const { data, isLoading, isError, status } = useLiveQuery((q) =>
71 * q.from({ todos: todoCollection })
72 * )
73 *
74 * if (isLoading) return <div>Loading...</div>
75 * if (isError) return <div>Error: {status}</div>
76 *
77 * return (
78 * <ul>
79 * {data.map(todo => <li key={todo.id}>{todo.text}</li>)}
80 * </ul>
81 * )
82 */
83// Overload 1: Accept query function that always returns QueryBuilder
84export function useLiveQuery<TContext extends Context>(
85 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
86 deps?: Array<unknown>,
87): {
88 state: Map<string | number, GetResult<TContext>>
89 data: InferResultType<TContext>
90 collection: Collection<GetResult<TContext>, string | number, {}>
91 status: CollectionStatus // Can't be disabled if always returns QueryBuilder
92 isLoading: boolean
93 isReady: boolean
94 isIdle: boolean
95 isError: boolean
96 isCleanedUp: boolean
97 isEnabled: true // Always true if always returns QueryBuilder
99​
100// Overload 2: Accept query function that can return undefined/null
101export function useLiveQuery<TContext extends Context>(
102 queryFn: (
103 q: InitialQueryBuilder,
104 ) => QueryBuilder<TContext> | undefined | null,
105 deps?: Array<unknown>,
106): {
107 state: Map<string | number, GetResult<TContext>> | undefined
108 data: InferResultType<TContext> | undefined
109 collection: Collection<GetResult<TContext>, string | number, {}> | undefined
110 status: UseLiveQueryStatus
111 isLoading: boolean
112 isReady: boolean
113 isIdle: boolean
114 isError: boolean
115 isCleanedUp: boolean
116 isEnabled: boolean
118​
119// Overload 3: Accept query function that can return LiveQueryCollectionConfig
120export function useLiveQuery<TContext extends Context>(
121 queryFn: (
122 q: InitialQueryBuilder,
123 ) => LiveQueryCollectionConfig<TContext> | undefined | null,
124 deps?: Array<unknown>,
125): {
126 state: Map<string | number, GetResult<TContext>> | undefined
127 data: InferResultType<TContext> | undefined
128 collection: Collection<GetResult<TContext>, string | number, {}> | undefined
129 status: UseLiveQueryStatus
130 isLoading: boolean
131 isReady: boolean
132 isIdle: boolean
133 isError: boolean
134 isCleanedUp: boolean
135 isEnabled: boolean
137​
138// Overload 4: Accept query function that can return Collection
139export function useLiveQuery<
140 TResult extends object,
141 TKey extends string | number,
142 TUtils extends Record<string, any>,
143>(
144 queryFn: (
145 q: InitialQueryBuilder,
146 ) => Collection<TResult, TKey, TUtils> | undefined | null,
147 deps?: Array<unknown>,
148): {
149 state: Map<TKey, TResult> | undefined
150 data: Array<TResult> | undefined
151 collection: Collection<TResult, TKey, TUtils> | undefined
152 status: UseLiveQueryStatus
153 isLoading: boolean
154 isReady: boolean
155 isIdle: boolean
156 isError: boolean
157 isCleanedUp: boolean
158 isEnabled: boolean
160​
161// Overload 5: Accept query function that can return all types
162export function useLiveQuery<
163 TContext extends Context,
164 TResult extends object,
165 TKey extends string | number,
166 TUtils extends Record<string, any>,
167>(
168 queryFn: (
169 q: InitialQueryBuilder,
170 ) =>
171 | QueryBuilder<TContext>
172 | LiveQueryCollectionConfig<TContext>
173 | Collection<TResult, TKey, TUtils>
174 | undefined
175 | null,
176 deps?: Array<unknown>,
177): {
178 state:
179 | Map<string | number, GetResult<TContext>>
180 | Map<TKey, TResult>
181 | undefined
182 data: InferResultType<TContext> | Array<TResult> | undefined
183 collection:
184 | Collection<GetResult<TContext>, string | number, {}>
185 | Collection<TResult, TKey, TUtils>
186 | undefined
187 status: UseLiveQueryStatus
188 isLoading: boolean
189 isReady: boolean
190 isIdle: boolean
191 isError: boolean
192 isCleanedUp: boolean
193 isEnabled: boolean
195​
196/**
197 * Create a live query using configuration object
198 * @param config - Configuration object with query and options
199 * @param deps - Array of dependencies that trigger query re-execution when changed
200 * @returns Object with reactive data, state, and status information
201 * @example
202 * // Basic config object usage
203 * const { data, status } = useLiveQuery({
204 * query: (q) => q.from({ todos: todosCollection }),
205 * gcTime: 60000
206 * })
207 *
208 * @example
209 * // With query builder and options
210 * const queryBuilder = new Query()
211 * .from({ persons: collection })
212 * .where(({ persons }) => gt(persons.age, 30))
213 * .select(({ persons }) => ({ id: persons.id, name: persons.name }))
214 *
215 * const { data, isReady } = useLiveQuery({ query: queryBuilder })
216 *
217 * @example
218 * // Handle all states uniformly
219 * const { data, isLoading, isReady, isError } = useLiveQuery({
220 * query: (q) => q.from({ items: itemCollection })
221 * })
222 *
223 * if (isLoading) return <div>Loading...</div>
224 * if (isError) return <div>Something went wrong</div>
225 * if (!isReady) return <div>Preparing...</div>
226 *
227 * return <div>{data.length} items loaded</div>
228 */
229// Overload 6: Accept config object
230export function useLiveQuery<TContext extends Context>(
231 config: LiveQueryCollectionConfig<TContext>,
232 deps?: Array<unknown>,
233): {
234 state: Map<string | number, GetResult<TContext>>
235 data: InferResultType<TContext>
236 collection: Collection<GetResult<TContext>, string | number, {}>
237 status: CollectionStatus // Can't be disabled for config objects
238 isLoading: boolean
239 isReady: boolean
240 isIdle: boolean
241 isError: boolean
242 isCleanedUp: boolean
243 isEnabled: true // Always true for config objects
245​
246/**
247 * Subscribe to an existing live query collection
248 * @param liveQueryCollection - Pre-created live query collection to subscribe to
249 * @returns Object with reactive data, state, and status information
250 * @example
251 * // Using pre-created live query collection
252 * const myLiveQuery = createLiveQueryCollection((q) =>
253 * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
254 * )
255 * const { data, collection } = useLiveQuery(myLiveQuery)
256 *
257 * @example
258 * // Access collection methods directly
259 * const { data, collection, isReady } = useLiveQuery(existingCollection)
260 *
261 * // Use collection for mutations
262 * const handleToggle = (id) => {
263 * collection.update(id, draft => { draft.completed = !draft.completed })
264 * }
265 *
266 * @example
267 * // Handle states consistently
268 * const { data, isLoading, isError } = useLiveQuery(sharedCollection)
269 *
270 * if (isLoading) return <div>Loading...</div>
271 * if (isError) return <div>Error loading data</div>
272 *
273 * return <div>{data.map(item => <Item key={item.id} {...item} />)}</div>
274 */
275// Overload 7: Accept pre-created live query collection
276export function useLiveQuery<
277 TResult extends object,
278 TKey extends string | number,
279 TUtils extends Record<string, any>,
280>(
281 liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,
282): {
283 state: Map<TKey, TResult>
284 data: Array<TResult>
285 collection: Collection<TResult, TKey, TUtils>
286 status: CollectionStatus // Can't be disabled for pre-created live query collections
287 isLoading: boolean
288 isReady: boolean
289 isIdle: boolean
290 isError: boolean
291 isCleanedUp: boolean
292 isEnabled: true // Always true for pre-created live query collections
294​
295// Overload 8: Accept pre-created live query collection with singleResult: true
296export function useLiveQuery<
297 TResult extends object,
298 TKey extends string | number,
299 TUtils extends Record<string, any>,
300>(
301 liveQueryCollection: Collection<TResult, TKey, TUtils> & SingleResult,
302): {
303 state: Map<TKey, TResult>
304 data: TResult | undefined
305 collection: Collection<TResult, TKey, TUtils> & SingleResult
306 status: CollectionStatus // Can't be disabled for pre-created live query collections
307 isLoading: boolean
308 isReady: boolean
309 isIdle: boolean
310 isError: boolean
311 isCleanedUp: boolean
312 isEnabled: true // Always true for pre-created live query collections
314​
315// Implementation - use function overloads to infer the actual collection type
316export function useLiveQuery(
317 configOrQueryOrCollection: any,
318 deps: Array<unknown> = [],
319) {
320 // Check if it's already a collection
321 const inputIsCollection = isCollection(configOrQueryOrCollection)
322​
323 const createCollection = (): Collection<
324 object,
325 string | number,
326 {}
327 > | null => {
328 if (inputIsCollection) {
329 // Warn when passing a collection directly with on-demand sync mode
330 // In on-demand mode, data is only loaded when queries with predicates request it
331 // Passing the collection directly doesn't provide any predicates, so no data loads
332 const syncMode = (
333 configOrQueryOrCollection as { config?: { syncMode?: string } }
334 ).config?.syncMode
335 if (syncMode === `on-demand`) {
336 console.warn(
337 `[useLiveQuery] Warning: Passing a collection with syncMode "on-demand" directly to useLiveQuery ` +
338 `will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.\n\n` +
339 `Instead, use a query builder function:\n` +
340 ` const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c))\n\n` +
341 `Or switch to syncMode "eager" if you want all data to sync automatically.`,
342 )
343 }
344 // It's already a collection, ensure sync is started for React hooks
345 configOrQueryOrCollection.startSyncImmediate()
346 return configOrQueryOrCollection
347 } else {
348 // Handle different callback return types
349 if (typeof configOrQueryOrCollection === `function`) {
350 // Call the function with a query builder to see what it returns
351 const queryBuilder = new BaseQueryBuilder() as InitialQueryBuilder
352 const result = configOrQueryOrCollection(queryBuilder)
353​
354 if (result === undefined || result === null) {
355 // Callback returned undefined/null - disabled query
356 return null
357 } else if (isCollection(result)) {
358 // Callback returned a Collection instance - use it directly
359 result.startSyncImmediate()
360 return result
361 } else if (result instanceof BaseQueryBuilder) {
362 // Callback returned QueryBuilder - create live query collection using the original callback
363 // (not the result, since the result might be from a different query builder instance)
364 return createLiveQueryCollection({
365 query: configOrQueryOrCollection,
366 startSync: true,
367 gcTime: DEFAULT_GC_TIME_MS,
368 })
369 } else if (result && typeof result === `object`) {
370 // Assume it's a LiveQueryCollectionConfig
371 return createLiveQueryCollection({
372 startSync: true,
373 gcTime: DEFAULT_GC_TIME_MS,
374 ...result,
375 })
376 } else {
377 // Unexpected return type
378 throw new Error(
379 `useLiveQuery callback must return a QueryBuilder, LiveQueryCollectionConfig, Collection, undefined, or null. Got: ${typeof result}`,
380 )
381 }
382 } else {
383 // Original logic for config objects
384 return createLiveQueryCollection({
385 startSync: true,
386 gcTime: DEFAULT_GC_TIME_MS,
387 ...configOrQueryOrCollection,
388 })
389 }
390 }
391 }
392​
393 // Use state to cache collection and track dependencies
394 const [collection, setCollection] = useState(createCollection)
395 const [prevCollection, setPrevCollection] = useState(collection)
396 const [prevDeps, setPrevDeps] = useState(
397 !inputIsCollection ? [...deps] : null,
398 )
399 const [prevConfig, setPrevConfig] = useState(
400 inputIsCollection ? configOrQueryOrCollection : null,
401 )
402​
403 // Check if we need to create/recreate the collection
404 const needsNewCollection =
405 (inputIsCollection && prevConfig !== configOrQueryOrCollection) ||
406 (!inputIsCollection &&
407 (prevDeps === null ||
408 prevDeps.length !== deps.length ||
409 prevDeps.some((dep, i) => dep !== deps[i])))
410​
411 if (needsNewCollection) {
412 setCollection(createCollection)
413 if (isCollection(configOrQueryOrCollection)) {
414 setPrevConfig(configOrQueryOrCollection)
415 } else {
416 setPrevDeps([...deps])
417 }
418 }
419​
420 // The shared observer owns subscription, the ready-race, and the snapshot.
421 const [observer, setObserver] = useState(() =>
422 // Defer the initial notify: useSyncExternalStore must not be notified
423 // synchronously during subscribe.
424 // Wholesale mode: React re-reads getSnapshot() on notify, keeps the
425 // hook's pre-observer loading policy, and — because wholesale delivers
426 // nothing synchronously during subscribe — never notifies
427 // useSyncExternalStore inside its own subscribe call.
428 createLiveQueryObserver(collection, { mode: `wholesale` }),
429 )
430​
431 // Recreate the observer when the underlying collection changes. The observer
432 // is not disposed explicitly here or on unmount: `useSyncExternalStore`
433 // unsubscribes it when the subscribe changes or the component unmounts, which
434 // detaches the collection subscription; the observer is then GC'd. (An unmount
435 // effect that disposed it would misfire under StrictMode/offscreen effect
436 // replay, leaving a disposed observer in the ref.)
437 if (prevCollection !== collection) {
438 setPrevCollection(collection)
439 setObserver(createLiveQueryObserver(collection, { mode: `wholesale` }))
440 }
441​
442 // Stable subscribe bound to the current observer; the observer owns the
443 // subscription, ready-race, and disposal.
444 const subscribe = useCallback(
445 (onStoreChange: () => void) => observer.subscribe(() => onStoreChange()),
446 [observer],
447 )
448​
449 const getSnapshot = useCallback(() => observer.getSnapshot(), [observer])
450​
451 // The observer returns a stable snapshot per revision, which is the return
452 // shape this hook exposes. Keep the return loose to satisfy the overloads.
453 return useSyncExternalStore(subscribe, getSnapshot) as any