Open History to see the last commit
1import { useRef, useSyncExternalStore } from "react"
2import {
3 BaseQueryBuilder,
4 CollectionImpl,
5 createLiveQueryCollection,
6} from "@tanstack/db"
7import type {
8 Collection,
9 CollectionStatus,
10 Context,
11 GetResult,
12 InitialQueryBuilder,
13 LiveQueryCollectionConfig,
14 QueryBuilder,
15} from "@tanstack/db"
16
17const DEFAULT_GC_TIME_MS = 1 // Live queries created by useLiveQuery are cleaned up immediately (0 disables GC)
18
19export type UseLiveQueryStatus = CollectionStatus | `disabled`
20
21/**
22 * Create a live query using a query function
23 * @param queryFn - Query function that defines what data to fetch
24 * @param deps - Array of dependencies that trigger query re-execution when changed
25 * @returns Object with reactive data, state, and status information
26 * @example
27 * // Basic query with object syntax
28 * const { data, isLoading } = useLiveQuery((q) =>
29 * q.from({ todos: todosCollection })
30 * .where(({ todos }) => eq(todos.completed, false))
31 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
32 * )
33 *
34 * @example
35 * // With dependencies that trigger re-execution
36 * const { data, state } = useLiveQuery(
37 * (q) => q.from({ todos: todosCollection })
38 * .where(({ todos }) => gt(todos.priority, minPriority)),
39 * [minPriority] // Re-run when minPriority changes
40 * )
41 *
42 * @example
43 * // Join pattern
44 * const { data } = useLiveQuery((q) =>
45 * q.from({ issues: issueCollection })
46 * .join({ persons: personCollection }, ({ issues, persons }) =>
47 * eq(issues.userId, persons.id)
48 * )
49 * .select(({ issues, persons }) => ({
50 * id: issues.id,
51 * title: issues.title,
52 * userName: persons.name
53 * }))
54 * )
55 *
56 * @example
57 * // Handle loading and error states
58 * const { data, isLoading, isError, status } = useLiveQuery((q) =>
59 * q.from({ todos: todoCollection })
60 * )
61 *
62 * if (isLoading) return <div>Loading...</div>
63 * if (isError) return <div>Error: {status}</div>
64 *
65 * return (
66 * <ul>
67 * {data.map(todo => <li key={todo.id}>{todo.text}</li>)}
68 * </ul>
69 * )
70 */
71// Overload 1: Accept query function that always returns QueryBuilder
72export function useLiveQuery<TContext extends Context>(
73 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
74 deps?: Array<unknown>
75): {
76 state: Map<string | number, GetResult<TContext>>
77 data: Array<GetResult<TContext>>
78 collection: Collection<GetResult<TContext>, string | number, {}>
79 status: CollectionStatus // Can't be disabled if always returns QueryBuilder
80 isLoading: boolean
81 isReady: boolean
82 isIdle: boolean
83 isError: boolean
84 isCleanedUp: boolean
85 isEnabled: true // Always true if always returns QueryBuilder
86}
87
88// Overload 2: Accept query function that can return undefined/null
89export function useLiveQuery<TContext extends Context>(
90 queryFn: (
91 q: InitialQueryBuilder
92 ) => QueryBuilder<TContext> | undefined | null,
93 deps?: Array<unknown>
94): {
95 state: Map<string | number, GetResult<TContext>> | undefined
96 data: Array<GetResult<TContext>> | undefined
97 collection: Collection<GetResult<TContext>, string | number, {}> | undefined
98 status: UseLiveQueryStatus
99 isLoading: boolean
100 isReady: boolean
101 isIdle: boolean
102 isError: boolean
103 isCleanedUp: boolean
104 isEnabled: boolean
105}
106
107// Overload 3: Accept query function that can return LiveQueryCollectionConfig
108export function useLiveQuery<TContext extends Context>(
109 queryFn: (
110 q: InitialQueryBuilder
111 ) => LiveQueryCollectionConfig<TContext> | undefined | null,
112 deps?: Array<unknown>
113): {
114 state: Map<string | number, GetResult<TContext>> | undefined
115 data: Array<GetResult<TContext>> | undefined
116 collection: Collection<GetResult<TContext>, string | number, {}> | undefined
117 status: UseLiveQueryStatus
118 isLoading: boolean
119 isReady: boolean
120 isIdle: boolean
121 isError: boolean
122 isCleanedUp: boolean
123 isEnabled: boolean
124}
125
126// Overload 4: Accept query function that can return Collection
127export function useLiveQuery<
128 TResult extends object,
129 TKey extends string | number,
130 TUtils extends Record<string, any>,
131>(
132 queryFn: (
133 q: InitialQueryBuilder
134 ) => Collection<TResult, TKey, TUtils> | undefined | null,
135 deps?: Array<unknown>
136): {
137 state: Map<TKey, TResult> | undefined
138 data: Array<TResult> | undefined
139 collection: Collection<TResult, TKey, TUtils> | undefined
140 status: UseLiveQueryStatus
141 isLoading: boolean
142 isReady: boolean
143 isIdle: boolean
144 isError: boolean
145 isCleanedUp: boolean
146 isEnabled: boolean
147}
148
149// Overload 5: Accept query function that can return all types
150export function useLiveQuery<
151 TContext extends Context,
152 TResult extends object,
153 TKey extends string | number,
154 TUtils extends Record<string, any>,
155>(
156 queryFn: (
157 q: InitialQueryBuilder
158 ) =>
159 | QueryBuilder<TContext>
160 | LiveQueryCollectionConfig<TContext>
161 | Collection<TResult, TKey, TUtils>
162 | undefined
163 | null,
164 deps?: Array<unknown>
165): {
166 state:
167 | Map<string | number, GetResult<TContext>>
168 | Map<TKey, TResult>
169 | undefined
170 data: Array<GetResult<TContext>> | Array<TResult> | undefined
171 collection:
172 | Collection<GetResult<TContext>, string | number, {}>
173 | Collection<TResult, TKey, TUtils>
174 | undefined
175 status: UseLiveQueryStatus
176 isLoading: boolean
177 isReady: boolean
178 isIdle: boolean
179 isError: boolean
180 isCleanedUp: boolean
181 isEnabled: boolean
182}
183
184/**
185 * Create a live query using configuration object
186 * @param config - Configuration object with query and options
187 * @param deps - Array of dependencies that trigger query re-execution when changed
188 * @returns Object with reactive data, state, and status information
189 * @example
190 * // Basic config object usage
191 * const { data, status } = useLiveQuery({
192 * query: (q) => q.from({ todos: todosCollection }),
193 * gcTime: 60000
194 * })
195 *
196 * @example
197 * // With query builder and options
198 * const queryBuilder = new Query()
199 * .from({ persons: collection })
200 * .where(({ persons }) => gt(persons.age, 30))
201 * .select(({ persons }) => ({ id: persons.id, name: persons.name }))
202 *
203 * const { data, isReady } = useLiveQuery({ query: queryBuilder })
204 *
205 * @example
206 * // Handle all states uniformly
207 * const { data, isLoading, isReady, isError } = useLiveQuery({
208 * query: (q) => q.from({ items: itemCollection })
209 * })
210 *
211 * if (isLoading) return <div>Loading...</div>
212 * if (isError) return <div>Something went wrong</div>
213 * if (!isReady) return <div>Preparing...</div>
214 *
215 * return <div>{data.length} items loaded</div>
216 */
217// Overload 6: Accept config object
218export function useLiveQuery<TContext extends Context>(
219 config: LiveQueryCollectionConfig<TContext>,
220 deps?: Array<unknown>
221): {
222 state: Map<string | number, GetResult<TContext>>
223 data: Array<GetResult<TContext>>
224 collection: Collection<GetResult<TContext>, string | number, {}>
225 status: CollectionStatus // Can't be disabled for config objects
226 isLoading: boolean
227 isReady: boolean
228 isIdle: boolean
229 isError: boolean
230 isCleanedUp: boolean
231 isEnabled: true // Always true for config objects
232}
233
234/**
235 * Subscribe to an existing live query collection
236 * @param liveQueryCollection - Pre-created live query collection to subscribe to
237 * @returns Object with reactive data, state, and status information
238 * @example
239 * // Using pre-created live query collection
240 * const myLiveQuery = createLiveQueryCollection((q) =>
241 * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
242 * )
243 * const { data, collection } = useLiveQuery(myLiveQuery)
244 *
245 * @example
246 * // Access collection methods directly
247 * const { data, collection, isReady } = useLiveQuery(existingCollection)
248 *
249 * // Use collection for mutations
250 * const handleToggle = (id) => {
251 * collection.update(id, draft => { draft.completed = !draft.completed })
252 * }
253 *
254 * @example
255 * // Handle states consistently
256 * const { data, isLoading, isError } = useLiveQuery(sharedCollection)
257 *
258 * if (isLoading) return <div>Loading...</div>
259 * if (isError) return <div>Error loading data</div>
260 *
261 * return <div>{data.map(item => <Item key={item.id} {...item} />)}</div>
262 */
263// Overload 7: Accept pre-created live query collection
264export function useLiveQuery<
265 TResult extends object,
266 TKey extends string | number,
267 TUtils extends Record<string, any>,
268>(
269 liveQueryCollection: Collection<TResult, TKey, TUtils>
270): {
271 state: Map<TKey, TResult>
272 data: Array<TResult>
273 collection: Collection<TResult, TKey, TUtils>
274 status: CollectionStatus // Can't be disabled for pre-created live query collections
275 isLoading: boolean
276 isReady: boolean
277 isIdle: boolean
278 isError: boolean
279 isCleanedUp: boolean
280 isEnabled: true // Always true for pre-created live query collections
281}
282
283// Implementation - use function overloads to infer the actual collection type
284export function useLiveQuery(
285 configOrQueryOrCollection: any,
286 deps: Array<unknown> = []
287) {
288 // Check if it's already a collection by checking for specific collection methods
289 const isCollection =
290 configOrQueryOrCollection &&
291 typeof configOrQueryOrCollection === `object` &&
292 typeof configOrQueryOrCollection.subscribeChanges === `function` &&
293 typeof configOrQueryOrCollection.startSyncImmediate === `function` &&
294 typeof configOrQueryOrCollection.id === `string`
295
296 // Use refs to cache collection and track dependencies
297 const collectionRef = useRef<Collection<object, string | number, {}> | null>(
298 null
299 )
300 const depsRef = useRef<Array<unknown> | null>(null)
301 const configRef = useRef<unknown>(null)
302
303 // Use refs to track version and memoized snapshot
304 const versionRef = useRef(0)
305 const snapshotRef = useRef<{
306 collection: Collection<object, string | number, {}> | null
307 version: number
308 } | null>(null)
309
310 // Check if we need to create/recreate the collection
311 const needsNewCollection =
312 !collectionRef.current ||
313 (isCollection && configRef.current !== configOrQueryOrCollection) ||
314 (!isCollection &&
315 (depsRef.current === null ||
316 depsRef.current.length !== deps.length ||
317 depsRef.current.some((dep, i) => dep !== deps[i])))
318
319 if (needsNewCollection) {
320 if (isCollection) {
321 // It's already a collection, ensure sync is started for React hooks
322 configOrQueryOrCollection.startSyncImmediate()
323 collectionRef.current = configOrQueryOrCollection
324 configRef.current = configOrQueryOrCollection
325 } else {
326 // Handle different callback return types
327 if (typeof configOrQueryOrCollection === `function`) {
328 // Call the function with a query builder to see what it returns
329 const queryBuilder = new BaseQueryBuilder() as InitialQueryBuilder
330 const result = configOrQueryOrCollection(queryBuilder)
331
332 if (result === undefined || result === null) {
333 // Callback returned undefined/null - disabled query
334 collectionRef.current = null
335 } else if (result instanceof CollectionImpl) {
336 // Callback returned a Collection instance - use it directly
337 result.startSyncImmediate()
338 collectionRef.current = result
339 } else if (result instanceof BaseQueryBuilder) {
340 // Callback returned QueryBuilder - create live query collection using the original callback
341 // (not the result, since the result might be from a different query builder instance)
342 collectionRef.current = createLiveQueryCollection({
343 query: configOrQueryOrCollection,
344 startSync: true,
345 gcTime: DEFAULT_GC_TIME_MS,
346 })
347 } else if (result && typeof result === `object`) {
348 // Assume it's a LiveQueryCollectionConfig
349 collectionRef.current = createLiveQueryCollection({
350 startSync: true,
351 gcTime: DEFAULT_GC_TIME_MS,
352 ...result,
353 })
354 } else {
355 // Unexpected return type
356 throw new Error(
357 `useLiveQuery callback must return a QueryBuilder, LiveQueryCollectionConfig, Collection, undefined, or null. Got: ${typeof result}`
358 )
359 }
360 depsRef.current = [...deps]
361 } else {
362 // Original logic for config objects
363 collectionRef.current = createLiveQueryCollection({
364 startSync: true,
365 gcTime: DEFAULT_GC_TIME_MS,
366 ...configOrQueryOrCollection,
367 })
368 depsRef.current = [...deps]
369 }
370 }
371 }
372
373 // Reset refs when collection changes
374 if (needsNewCollection) {
375 versionRef.current = 0
376 snapshotRef.current = null
377 }
378
379 // Create stable subscribe function using ref
380 const subscribeRef = useRef<
381 ((onStoreChange: () => void) => () => void) | null
382 >(null)
383 if (!subscribeRef.current || needsNewCollection) {
384 subscribeRef.current = (onStoreChange: () => void) => {
385 // If no collection, return a no-op unsubscribe function
386 if (!collectionRef.current) {
387 return () => {}
388 }
389
390 const subscription = collectionRef.current.subscribeChanges(() => {
391 // Bump version on any change; getSnapshot will rebuild next time
392 versionRef.current += 1
393 onStoreChange()
394 })
395 // Collection may be ready and will not receive initial `subscribeChanges()`
396 if (collectionRef.current.status === `ready`) {
397 versionRef.current += 1
398 onStoreChange()
399 }
400 return () => {
401 subscription.unsubscribe()
402 }
403 }
404 }
405
406 // Create stable getSnapshot function using ref
407 const getSnapshotRef = useRef<
408 | (() => {
409 collection: Collection<object, string | number, {}> | null
410 version: number
411 })
412 | null
413 >(null)
414 if (!getSnapshotRef.current || needsNewCollection) {
415 getSnapshotRef.current = () => {
416 const currentVersion = versionRef.current
417 const currentCollection = collectionRef.current
418
419 // Recreate snapshot object only if version/collection changed
420 if (
421 !snapshotRef.current ||
422 snapshotRef.current.version !== currentVersion ||
423 snapshotRef.current.collection !== currentCollection
424 ) {
425 snapshotRef.current = {
426 collection: currentCollection,
427 version: currentVersion,
428 }
429 }
430
431 return snapshotRef.current
432 }
433 }
434
435 // Use useSyncExternalStore to subscribe to collection changes
436 const snapshot = useSyncExternalStore(
437 subscribeRef.current,
438 getSnapshotRef.current
439 )
440
441 // Track last snapshot (from useSyncExternalStore) and the returned value separately
442 const returnedSnapshotRef = useRef<{
443 collection: Collection<object, string | number, {}> | null
444 version: number
445 } | null>(null)
446 // Keep implementation return loose to satisfy overload signatures
447 const returnedRef = useRef<any>(null)
448
449 // Rebuild returned object only when the snapshot changes (version or collection identity)
450 if (
451 !returnedSnapshotRef.current ||
452 returnedSnapshotRef.current.version !== snapshot.version ||
453 returnedSnapshotRef.current.collection !== snapshot.collection
454 ) {
455 // Handle null collection case (when callback returns undefined/null)
456 if (!snapshot.collection) {
457 returnedRef.current = {
458 state: undefined,
459 data: undefined,
460 collection: undefined,
461 status: `disabled`,
462 isLoading: false,
463 isReady: false,
464 isIdle: false,
465 isError: false,
466 isCleanedUp: false,
467 isEnabled: false,
468 }
469 } else {
470 // Capture a stable view of entries for this snapshot to avoid tearing
471 const entries = Array.from(snapshot.collection.entries())
472 let stateCache: Map<string | number, unknown> | null = null
473 let dataCache: Array<unknown> | null = null
474
475 returnedRef.current = {
476 get state() {
477 if (!stateCache) {
478 stateCache = new Map(entries)
479 }
480 return stateCache
481 },
482 get data() {
483 if (!dataCache) {
484 dataCache = entries.map(([, value]) => value)
485 }
486 return dataCache
487 },
488 collection: snapshot.collection,
489 status: snapshot.collection.status,
490 isLoading:
491 snapshot.collection.status === `loading` ||
492 snapshot.collection.status === `initialCommit`,
493 isReady: snapshot.collection.status === `ready`,
494 isIdle: snapshot.collection.status === `idle`,
495 isError: snapshot.collection.status === `error`,
496 isCleanedUp: snapshot.collection.status === `cleaned-up`,
497 isEnabled: true,
498 }
499 }
500
501 // Remember the snapshot that produced this returned value
502 returnedSnapshotRef.current = snapshot
503 }
504
505 return returnedRef.current!
506}