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

useLiveQuery.ts

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