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

useLiveQuery.ts

588 lines17.6 KB

1import {
2 batch,
3 createEffect,
4 createMemo,
5 createResource,
6 createSignal,
7 onCleanup,
8} from 'solid-js'
9import { ReactiveMap } from '@solid-primitives/map'
10import {
11 BaseQueryBuilder,
12 createLiveQueryObserver,
13 getLiveQueryStatusFlags,
14 getPublicCollection,
15 isCollection,
16 isSingleResultCollection,
17 resolveLiveQueryValue,
18 toBoundaryError,
19} from '@tanstack/db'
20import { createStore, reconcile } from 'solid-js/store'
21import type { Accessor } from 'solid-js'
22import type {
23 ChangeMessage,
24 Collection,
25 CollectionStatus,
26 Context,
27 GetResult,
28 HealthNode,
29 InferResultType,
30 InitialQueryBuilder,
31 LiveQueryHookConfig,
32 LiveQueryObserver,
33 LiveQueryStatusFlags,
34 NonSingleResult,
35 QueryBuilder,
36 SingleResult,
37} from '@tanstack/db'
38​
39const DEFAULT_GC_TIME_MS = 1
40​
41type InferConditionalResultType<TContext extends Context> =
42 TContext extends SingleResult
43 ? InferResultType<TContext> | []
44 : InferResultType<TContext>
45​
46/**
47 * Create a live query using a query function
48 * @param queryFn - Query function that defines what data to fetch
49 * @returns Accessor that returns data with Suspense support, with state and status information as properties
50 * @example
51 * // Basic query with object syntax
52 * const todosQuery = useLiveQuery((q) =>
53 * q.from({ todos: todosCollection })
54 * .where(({ todos }) => eq(todos.completed, false))
55 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
56 * )
57 *
58 * @example
59 * // With dependencies that trigger re-execution
60 * const todosQuery = useLiveQuery(
61 * (q) => q.from({ todos: todosCollection })
62 * .where(({ todos }) => gt(todos.priority, minPriority())),
63 * )
64 *
65 * @example
66 * // Join pattern
67 * const personIssues = useLiveQuery((q) =>
68 * q.from({ issues: issueCollection })
69 * .join({ persons: personCollection }, ({ issues, persons }) =>
70 * eq(issues.userId, persons.id)
71 * )
72 * .select(({ issues, persons }) => ({
73 * id: issues.id,
74 * title: issues.title,
75 * userName: persons.name
76 * }))
77 * )
78 *
79 * @example
80 * // Handle loading and error states
81 * const todosQuery = useLiveQuery((q) =>
82 * q.from({ todos: todoCollection })
83 * )
84 *
85 * return (
86 * <Switch>
87 * <Match when={todosQuery.isLoading}>
88 * <div>Loading...</div>
89 * </Match>
90 * <Match when={todosQuery.isLoadingError}>
91 * <div>Error: {todosQuery.status}</div>
92 * </Match>
93 * <Match when={todosQuery.isReady}>
94 * <For each={todosQuery()}>
95 * {(todo) => <li key={todo.id}>{todo.text}</li>}
96 * </For>
97 * </Match>
98 * </Switch>
99 * )
100 *
101 * @example
102 * // Use Suspense boundaries
103 * const todosQuery = useLiveQuery((q) =>
104 * q.from({ todos: todoCollection })
105 * )
106 *
107 * return (
108 * <Suspense fallback={<div>Loading...</div>}>
109 * <For each={todosQuery()}>
110 * {(todo) => <li key={todo.id}>{todo.text}</li>}
111 * </For>
112 * </Suspense>
113 * )
114 */
115​
116// Overload 1: Accept query function that always returns QueryBuilder
117export function useLiveQuery<TContext extends Context>(
118 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
119): Accessor<InferResultType<TContext>> & {
120 state: ReactiveMap<string | number, GetResult<TContext>>
121 collection: Collection<GetResult<TContext>, string | number, {}>
122 status: CollectionStatus
123} & LiveQueryStatusFlags
124​
125// Overload 1b: Accept query function that can return undefined/null
126export function useLiveQuery<TContext extends Context>(
127 queryFn: (
128 q: InitialQueryBuilder,
129 ) => QueryBuilder<TContext> | undefined | null,
130): Accessor<InferConditionalResultType<TContext>> & {
131 state: ReactiveMap<string | number, GetResult<TContext>>
132 collection: Collection<GetResult<TContext>, string | number, {}> | null
133 status: CollectionStatus | `disabled`
134} & LiveQueryStatusFlags
135​
136/**
137 * Create a live query using configuration object
138 * @param config - Configuration object with query and options
139 * @returns Accessor that returns data with Suspense support, with state and status information as properties
140 * @example
141 * // Basic config object usage
142 * const todosQuery = useLiveQuery(() => ({
143 * query: (q) => q.from({ todos: todosCollection }),
144 * gcTime: 60000
145 * }))
146 *
147 * @example
148 * // With query builder and options
149 * const queryBuilder = new Query()
150 * .from({ persons: collection })
151 * .where(({ persons }) => gt(persons.age, 30))
152 * .select(({ persons }) => ({ id: persons.id, name: persons.name }))
153 *
154 * const personsQuery = useLiveQuery(() => ({ query: queryBuilder }))
155 *
156 * @example
157 * // Handle all states uniformly
158 * const itemsQuery = useLiveQuery(() => ({
159 * query: (q) => q.from({ items: itemCollection })
160 * }))
161 *
162 * return (
163 * <Switch fallback={<div>{itemsQuery().length} items loaded</div>}>
164 * <Match when={itemsQuery.isLoading}>
165 * <div>Loading...</div>
166 * </Match>
167 * <Match when={itemsQuery.isLoadingError}>
168 * <div>Something went wrong</div>
169 * </Match>
170 * <Match when={!itemsQuery.isReady}>
171 * <div>Preparing...</div>
172 * </Match>
173 * </Switch>
174 * )
175 */
176// Overload 2: Accept config object
177export function useLiveQuery<TContext extends Context>(
178 config: Accessor<LiveQueryHookConfig<TContext>>,
179): Accessor<InferResultType<TContext>> & {
180 state: ReactiveMap<string | number, GetResult<TContext>>
181 collection: Collection<GetResult<TContext>, string | number, {}>
182 status: CollectionStatus
183} & LiveQueryStatusFlags
184​
185/**
186 * Subscribe to an existing live query collection
187 * @param liveQueryCollection - Pre-created live query collection to subscribe to
188 * @returns Accessor that returns data with Suspense support, with state and status information as properties
189 * @example
190 * // Using pre-created live query collection
191 * const myLiveQuery = createLiveQueryCollection((q) =>
192 * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
193 * )
194 * const todosQuery = useLiveQuery(() => myLiveQuery)
195 *
196 * @example
197 * // Access collection methods directly
198 * const existingQuery = useLiveQuery(() => existingCollection)
199 *
200 * // Use collection for mutations
201 * const handleToggle = (id) => {
202 * existingQuery.collection.update(id, draft => { draft.completed = !draft.completed })
203 * }
204 *
205 * @example
206 * // Handle states consistently
207 * const sharedQuery = useLiveQuery(() => sharedCollection)
208 *
209 * return (
210 * <Switch fallback={<div><For each={sharedQuery()}>{(item) => <Item key={item.id} {...item} />}</For></div>}>
211 * <Match when={sharedQuery.isLoading}>
212 * <div>Loading...</div>
213 * </Match>
214 * <Match when={sharedQuery.isLoadingError}>
215 * <div>Error loading data</div>
216 * </Match>
217 * </Switch>
218 * )
219 */
220// Overload 3: Accept pre-created live query collection (non-single result)
221export function useLiveQuery<
222 TResult extends object,
223 TKey extends string | number,
224 TUtils extends Record<string, any>,
225>(
226 liveQueryCollection: Accessor<
227 Collection<TResult, TKey, TUtils> & NonSingleResult
228 >,
229): Accessor<Array<TResult>> & {
230 state: ReactiveMap<TKey, TResult>
231 collection: Collection<TResult, TKey, TUtils>
232 status: CollectionStatus
233} & LiveQueryStatusFlags
234​
235// Overload 3b: Accept pre-created live query collection with singleResult: true
236export function useLiveQuery<
237 TResult extends object,
238 TKey extends string | number,
239 TUtils extends Record<string, any>,
240>(
241 liveQueryCollection: Accessor<
242 Collection<TResult, TKey, TUtils> & SingleResult
243 >,
244): Accessor<TResult | undefined> & {
245 state: ReactiveMap<TKey, TResult>
246 collection: Collection<TResult, TKey, TUtils> & SingleResult
247 status: CollectionStatus
248} & LiveQueryStatusFlags
249​
250// Implementation - use function overloads to infer the actual collection type
251export function useLiveQuery(
252 configOrQueryOrCollection: (queryFn?: any) => any,
253) {
254 const collection = createMemo(
255 () => {
256 if (configOrQueryOrCollection.length === 1) {
257 // This is a query function - check if it returns null/undefined
258 const queryBuilder = new BaseQueryBuilder() as InitialQueryBuilder
259 const result = configOrQueryOrCollection(queryBuilder)
260​
261 if (result === undefined || result === null) {
262 // Disabled query - return null
263 return null
264 }
265​
266 return resolveLiveQueryValue(result, { gcTime: DEFAULT_GC_TIME_MS })
267 }
268​
269 const innerCollection = configOrQueryOrCollection()
270​
271 if (innerCollection === undefined || innerCollection === null) {
272 // Disabled query - return null
273 return null
274 }
275​
276 if (isCollection(innerCollection)) {
277 innerCollection.startSyncImmediate()
278 return innerCollection as Collection
279 }
280​
281 return resolveLiveQueryValue(innerCollection, {
282 gcTime: DEFAULT_GC_TIME_MS,
283 })
284 },
285 undefined,
286 { name: `TanstackDBCollectionMemo` },
287 )
288​
289 // Reactive state that gets updated granularly through change events
290 const state = new ReactiveMap<string | number, any>()
291​
292 // Keep the live Collection's result keys private while preserving one stable
293 // Solid store per logical row. A row's public $key can belong to an upstream
294 // Collection and is therefore not necessarily unique in this result.
295 const rowsByKey = new Map<
296 string | number,
297 { value: any; update: (value: any) => void }
298 >()
299 let rowsCollection: Collection<any, any, any> | undefined
300 const [data, setData] = createStore<Array<any>>([], {
301 name: `TanstackDBData`,
302 })
303​
304 // Track collection status reactively
305 const [status, setStatus] = createSignal(
306 collection() ? collection()!.status : (`disabled` as const),
307 {
308 name: `TanstackDBStatus`,
309 },
310 )
311 const [health, setHealth] = createSignal<HealthNode | undefined>(undefined)
312 // Every status flag comes from the shared rule; a disabled query is ready.
313 const flags = createMemo(() =>
314 getLiveQueryStatusFlags(status() as CollectionStatus, health()),
315 )
316​
317 // Helper to sync data array from collection in correct order
318 const syncDataFromCollection = (
319 currentCollection: Collection<any, any, any>,
320 ) => {
321 const nextRows: Array<any> = []
322 const retainedKeys = new Set<string | number>()
323​
324 for (const [key, value] of currentCollection.entries()) {
325 retainedKeys.add(key)
326​
327 const existing = rowsByKey.get(key)
328 if (existing) {
329 existing.update(value)
330 nextRows.push(existing.value)
331 } else {
332 const [row, setRow] = createStore(value)
333 rowsByKey.set(key, {
334 value: row,
335 update: (nextValue) => setRow(reconcile(nextValue, { key: null })),
336 })
337 nextRows.push(row)
338 }
339 }
340​
341 for (const key of rowsByKey.keys()) {
342 if (!retainedKeys.has(key)) rowsByKey.delete(key)
343 }
344​
345 setData((previous) => reconcile(nextRows, { key: null })(previous))
346 }
347​
348 // Generation guard for the resource's async continuations: Solid discards a
349 // superseded fetch's *return value*, but the writes below are side effects
350 // into hook-scoped state and would still run — resurrecting rows/status from
351 // a collection that has already been replaced.
352 let resourceGeneration = 0
353 let localWait:
354 | {
355 observer: LiveQueryObserver<any, any>
356 collection: Collection<any, any, any>
357 ready: boolean
358 }
359 | undefined
360 let subscribedCollection: Collection<any, any, any> | undefined
361 const releaseLocalWait = () => {
362 localWait?.observer.dispose()
363 localWait = undefined
364 }
365 onCleanup(() => {
366 resourceGeneration++
367 releaseLocalWait()
368 })
369​
370 const [getDataResource] = createResource(
371 () => ({ currentCollection: collection() }),
372 async ({ currentCollection }) => {
373 const generation = ++resourceGeneration
374 releaseLocalWait()
375 if (!currentCollection) {
376 return []
377 }
378 setStatus(currentCollection.status)
379 setHealth(currentCollection.health)
380 try {
381 const observer = createLiveQueryObserver(currentCollection)
382 localWait = {
383 observer,
384 collection: currentCollection,
385 ready: false,
386 }
387 try {
388 await observer.preload()
389 } catch (error) {
390 if (generation === resourceGeneration) releaseLocalWait()
391 throw error
392 }
393 if (generation !== resourceGeneration) return data
394 localWait.ready = true
395 // `preload` waits for readiness but does not itself
396 // retain the Collection after it settles. Hold one observer
397 // subscription across Solid's ready-before-commit Suspense gap.
398 observer.subscribe(() => {})
399 // Solid disposes a provisional effect only after the resource settles
400 // and Suspense re-evaluates the branch. Check on the next turn: a real
401 // commit still owns the Collection, while a suspended branch keeps the
402 // preload observer until its later commit or root cleanup.
403 setTimeout(() => {
404 if (
405 localWait?.observer === observer &&
406 subscribedCollection === currentCollection
407 ) {
408 releaseLocalWait()
409 }
410 }, 0)
411 } catch (error) {
412 if (generation !== resourceGeneration) return data
413 // A crashed Collection also rejects preload; keep its crash visible.
414 setStatus(currentCollection.status === `crashed` ? `crashed` : `error`)
415 throw toBoundaryError(error)
416 }
417 if (generation !== resourceGeneration) {
418 return data
419 }
420 // Initialize state with current collection data
421 batch(() => {
422 state.clear()
423 for (const [key, value] of currentCollection.entries()) {
424 state.set(key, value)
425 }
426 syncDataFromCollection(currentCollection)
427 setStatus(currentCollection.status)
428 setHealth(currentCollection.health)
429 })
430 return data
431 },
432 {
433 name: `TanstackDBData`,
434 deferStream: false,
435 initialValue: data,
436 },
437 )
438​
439 createEffect(() => {
440 const currentCollection = collection()
441 if (!currentCollection) {
442 setStatus(`disabled` as const)
443 setHealth(undefined)
444 state.clear()
445 rowsByKey.clear()
446 rowsCollection = undefined
447 setData([])
448 return
449 }
450​
451 if (rowsCollection !== currentCollection) {
452 rowsByKey.clear()
453 rowsCollection = currentCollection
454 }
455​
456 // The shared observer owns subscription, the ready-race, and status; Solid
457 // materializes into its keyed ReactiveMap (granular) + reconciled store.
458 const observer = createLiveQueryObserver(currentCollection)
459 // Clear any keys carried over from a previous collection before the new
460 // observer re-seeds via `includeInitialState` (which only inserts current
461 // rows, never deletes stale ones). Without this, switching collections
462 // leaves the dropped keys in `state` until the async resource reconciles.
463 state.clear()
464 const unsubscribe = observer.subscribe(
465 (changes: Array<ChangeMessage<any>> | undefined) => {
466 batch(() => {
467 if (changes) {
468 for (const change of changes) {
469 switch (change.type) {
470 case `insert`:
471 case `update`:
472 state.set(change.key, change.value)
473 break
474 case `delete`:
475 state.delete(change.key)
476 break
477 }
478 }
479 } else {
480 // Cleanup and other status-only publications carry no row deltas.
481 // Rebuild the keyed view so it cannot diverge from ordered data.
482 state.clear()
483 for (const [key, value] of observer.getSnapshot().state ?? []) {
484 state.set(key, value)
485 }
486 }
487 syncDataFromCollection(currentCollection)
488 const snapshot = observer.getSnapshot()
489 setStatus(snapshot.status)
490 setHealth(snapshot.health)
491 })
492 },
493 )
494 subscribedCollection = currentCollection
495 if (localWait?.ready && localWait.collection === currentCollection) {
496 releaseLocalWait()
497 }
498 // An already-ready empty collection produces no initial row batch. Bring
499 // ordered data and status in line synchronously instead of waiting for the
500 // resource continuation to correct the previous collection's rows.
501 batch(() => {
502 syncDataFromCollection(currentCollection)
503 const snapshot = observer.getSnapshot()
504 setStatus(snapshot.status)
505 setHealth(snapshot.health)
506 })
507​
508 onCleanup(() => {
509 if (subscribedCollection === currentCollection) {
510 subscribedCollection = undefined
511 }
512 unsubscribe()
513 observer.dispose()
514 })
515 })
516​
517 // We have to remove getters from the resource function so we wrap it
518 function getData() {
519 const currentCollection = collection()
520 if (currentCollection) {
521 if (isSingleResultCollection(currentCollection)) {
522 // Force resource tracking so Suspense works
523 getDataResource()
524 return data[0]
525 }
526 }
527 return getDataResource()
528 }
529​
530 Object.defineProperties(getData, {
531 status: {
532 get() {
533 return status()
534 },
535 },
536 collection: {
537 get() {
538 return getPublicCollection(collection())
539 },
540 },
541 state: {
542 get() {
543 return state
544 },
545 },
546 isLoading: {
547 get() {
548 return flags().isLoading
549 },
550 },
551 isReady: {
552 get() {
553 return flags().isReady || status() === `disabled`
554 },
555 },
556 isIdle: {
557 get() {
558 return flags().isIdle
559 },
560 },
561 isLoadingError: {
562 get() {
563 return flags().isLoadingError
564 },
565 },
566 isCrashed: {
567 get() {
568 return flags().isCrashed
569 },
570 },
571 isCleanedUp: {
572 get() {
573 return flags().isCleanedUp
574 },
575 },
576 isSyncError: {
577 get() {
578 return flags().isSyncError
579 },
580 },
581 health: {
582 get() {
583 return health()
584 },
585 },
586 })
587 return getData