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