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

useLiveQuery.ts

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