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