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

useLiveQuery.ts

589 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 { createRowStore, createStoreReadView } 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 const readData = createStoreReadView(data)
306​
307 // Track collection status reactively
308 const [status, setStatus] = createSignal(
309 collection() ? collection()!.status : (`disabled` as const),
310 {
311 name: `TanstackDBStatus`,
312 },
313 )
314 const [health, setHealth] = createSignal<HealthNode | undefined>(undefined)
315 // Every status flag comes from the shared rule; a disabled query is ready.
316 const flags = createMemo(() =>
317 getLiveQueryStatusFlags(status() as CollectionStatus, health()),
318 )
319​
320 // Helper to sync data array from collection in correct order
321 const syncDataFromCollection = (
322 currentCollection: Collection<any, any, any>,
323 ) => {
324 const nextRows: Array<any> = []
325 const retainedKeys = new Set<string | number>()
326​
327 for (const [key, value] of currentCollection.entries()) {
328 retainedKeys.add(key)
329​
330 const existing = rowsByKey.get(key)
331 if (existing) {
332 existing.update(value)
333 nextRows.push(existing.value)
334 } else {
335 const row = createRowStore(value)
336 rowsByKey.set(key, row)
337 nextRows.push(row.value)
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 readData[0]
525 }
526 }
527 const result = getDataResource()
528 return result === data ? readData : result
529 }
530​
531 Object.defineProperties(getData, {
532 status: {
533 get() {
534 return status()
535 },
536 },
537 collection: {
538 get() {
539 return getPublicCollection(collection())
540 },
541 },
542 state: {
543 get() {
544 return state
545 },
546 },
547 isLoading: {
548 get() {
549 return flags().isLoading
550 },
551 },
552 isReady: {
553 get() {
554 return flags().isReady || status() === `disabled`
555 },
556 },
557 isIdle: {
558 get() {
559 return flags().isIdle
560 },
561 },
562 isLoadingError: {
563 get() {
564 return flags().isLoadingError
565 },
566 },
567 isCrashed: {
568 get() {
569 return flags().isCrashed
570 },
571 },
572 isCleanedUp: {
573 get() {
574 return flags().isCleanedUp
575 },
576 },
577 isSyncError: {
578 get() {
579 return flags().isSyncError
580 },
581 },
582 health: {
583 get() {
584 return health()
585 },
586 },
587 })
588 return getData