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

useLiveQuery.ts

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