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

useLiveQuery.ts

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