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 CollectionImpl,
13 createLiveQueryCollection,
14} from '@tanstack/db'
15import { createStore, reconcile } from 'solid-js/store'
16import type { Accessor } from 'solid-js'
17import type {
18 ChangeMessage,
19 Collection,
20 CollectionStatus,
21 Context,
22 GetResult,
23 InitialQueryBuilder,
24 LiveQueryCollectionConfig,
25 QueryBuilder,
26} from '@tanstack/db'
27
28/**
29 * Create a live query using a query function
30 * @param queryFn - Query function that defines what data to fetch
31 * @returns Accessor that returns data with Suspense support, with state and status information as properties
32 * @example
33 * // Basic query with object syntax
34 * const todosQuery = useLiveQuery((q) =>
35 * q.from({ todos: todosCollection })
36 * .where(({ todos }) => eq(todos.completed, false))
37 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
38 * )
39 *
40 * @example
41 * // With dependencies that trigger re-execution
42 * const todosQuery = useLiveQuery(
43 * (q) => q.from({ todos: todosCollection })
44 * .where(({ todos }) => gt(todos.priority, minPriority())),
45 * )
46 *
47 * @example
48 * // Join pattern
49 * const personIssues = useLiveQuery((q) =>
50 * q.from({ issues: issueCollection })
51 * .join({ persons: personCollection }, ({ issues, persons }) =>
52 * eq(issues.userId, persons.id)
53 * )
54 * .select(({ issues, persons }) => ({
55 * id: issues.id,
56 * title: issues.title,
57 * userName: persons.name
58 * }))
59 * )
60 *
61 * @example
62 * // Handle loading and error states
63 * const todosQuery = useLiveQuery((q) =>
64 * q.from({ todos: todoCollection })
65 * )
66 *
67 * return (
68 * <Switch>
69 * <Match when={todosQuery.isLoading}>
70 * <div>Loading...</div>
71 * </Match>
72 * <Match when={todosQuery.isError}>
73 * <div>Error: {todosQuery.status}</div>
74 * </Match>
75 * <Match when={todosQuery.isReady}>
76 * <For each={todosQuery()}>
77 * {(todo) => <li key={todo.id}>{todo.text}</li>}
78 * </For>
79 * </Match>
80 * </Switch>
81 * )
82 *
83 * @example
84 * // Use Suspense boundaries
85 * const todosQuery = useLiveQuery((q) =>
86 * q.from({ todos: todoCollection })
87 * )
88 *
89 * return (
90 * <Suspense fallback={<div>Loading...</div>}>
91 * <For each={todosQuery()}>
92 * {(todo) => <li key={todo.id}>{todo.text}</li>}
93 * </For>
94 * </Suspense>
95 * )
96 */
97// Overload 1: Accept query function that always returns QueryBuilder
98export function useLiveQuery<TContext extends Context>(
99 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
100): Accessor<Array<GetResult<TContext>>> & {
101 /**
102 * @deprecated use function result instead
103 * query.data -> query()
104 */
105 data: Array<GetResult<TContext>>
106 state: ReactiveMap<string | number, GetResult<TContext>>
107 collection: Collection<GetResult<TContext>, string | number, {}>
108 status: CollectionStatus
109 isLoading: boolean
110 isReady: boolean
111 isIdle: boolean
112 isError: boolean
113 isCleanedUp: boolean
114}
115
116// Overload 1b: Accept query function that can return undefined/null
117export function useLiveQuery<TContext extends Context>(
118 queryFn: (
119 q: InitialQueryBuilder,
120 ) => QueryBuilder<TContext> | undefined | null,
121): Accessor<Array<GetResult<TContext>>> & {
122 /**
123 * @deprecated use function result instead
124 * query.data -> query()
125 */
126 data: Array<GetResult<TContext>>
127 state: ReactiveMap<string | number, GetResult<TContext>>
128 collection: Collection<GetResult<TContext>, string | number, {}> | null
129 status: CollectionStatus | `disabled`
130 isLoading: boolean
131 isReady: boolean
132 isIdle: boolean
133 isError: boolean
134 isCleanedUp: boolean
135}
136
137/**
138 * Create a live query using configuration object
139 * @param config - Configuration object with query and options
140 * @returns Accessor that returns data with Suspense support, with state and status information as properties
141 * @example
142 * // Basic config object usage
143 * const todosQuery = useLiveQuery(() => ({
144 * query: (q) => q.from({ todos: todosCollection }),
145 * gcTime: 60000
146 * }))
147 *
148 * @example
149 * // With query builder and options
150 * const queryBuilder = new Query()
151 * .from({ persons: collection })
152 * .where(({ persons }) => gt(persons.age, 30))
153 * .select(({ persons }) => ({ id: persons.id, name: persons.name }))
154 *
155 * const personsQuery = useLiveQuery(() => ({ query: queryBuilder }))
156 *
157 * @example
158 * // Handle all states uniformly
159 * const itemsQuery = useLiveQuery(() => ({
160 * query: (q) => q.from({ items: itemCollection })
161 * }))
162 *
163 * return (
164 * <Switch fallback={<div>{itemsQuery().length} items loaded</div>}>
165 * <Match when={itemsQuery.isLoading}>
166 * <div>Loading...</div>
167 * </Match>
168 * <Match when={itemsQuery.isError}>
169 * <div>Something went wrong</div>
170 * </Match>
171 * <Match when={!itemsQuery.isReady}>
172 * <div>Preparing...</div>
173 * </Match>
174 * </Switch>
175 * )
176 */
177// Overload 2: Accept config object
178export function useLiveQuery<TContext extends Context>(
179 config: Accessor<LiveQueryCollectionConfig<TContext>>,
180): Accessor<Array<GetResult<TContext>>> & {
181 /**
182 * @deprecated use function result instead
183 * query.data -> query()
184 */
185 data: Array<GetResult<TContext>>
186 state: ReactiveMap<string | number, GetResult<TContext>>
187 collection: Collection<GetResult<TContext>, string | number, {}>
188 status: CollectionStatus
189 isLoading: boolean
190 isReady: boolean
191 isIdle: boolean
192 isError: boolean
193 isCleanedUp: boolean
194}
195
196/**
197 * Subscribe to an existing live query collection
198 * @param liveQueryCollection - Pre-created live query collection to subscribe to
199 * @returns Accessor that returns data with Suspense support, with state and status information as properties
200 * @example
201 * // Using pre-created live query collection
202 * const myLiveQuery = createLiveQueryCollection((q) =>
203 * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
204 * )
205 * const todosQuery = useLiveQuery(() => myLiveQuery)
206 *
207 * @example
208 * // Access collection methods directly
209 * const existingQuery = useLiveQuery(() => existingCollection)
210 *
211 * // Use collection for mutations
212 * const handleToggle = (id) => {
213 * existingQuery.collection.update(id, draft => { draft.completed = !draft.completed })
214 * }
215 *
216 * @example
217 * // Handle states consistently
218 * const sharedQuery = useLiveQuery(() => sharedCollection)
219 *
220 * return (
221 * <Switch fallback={<div><For each={sharedQuery()}>{(item) => <Item key={item.id} {...item} />}</For></div>}>
222 * <Match when={sharedQuery.isLoading}>
223 * <div>Loading...</div>
224 * </Match>
225 * <Match when={sharedQuery.isError}>
226 * <div>Error loading data</div>
227 * </Match>
228 * </Switch>
229 * )
230 */
231// Overload 3: Accept pre-created live query collection
232export function useLiveQuery<
233 TResult extends object,
234 TKey extends string | number,
235 TUtils extends Record<string, any>,
236>(
237 liveQueryCollection: Accessor<Collection<TResult, TKey, TUtils>>,
238): Accessor<Array<TResult>> & {
239 /**
240 * @deprecated use function result instead
241 * query.data -> query()
242 */
243 data: Array<TResult>
244 state: ReactiveMap<TKey, TResult>
245 collection: Collection<TResult, TKey, TUtils>
246 status: CollectionStatus
247 isLoading: boolean
248 isReady: boolean
249 isIdle: boolean
250 isError: boolean
251 isCleanedUp: boolean
252}
253
254// Implementation - use function overloads to infer the actual collection type
255export function useLiveQuery(
256 configOrQueryOrCollection: (queryFn?: any) => any,
257) {
258 const collection = createMemo(
259 () => {
260 if (configOrQueryOrCollection.length === 1) {
261 // This is a query function - check if it returns null/undefined
262 const queryBuilder = new BaseQueryBuilder() as InitialQueryBuilder
263 const result = configOrQueryOrCollection(queryBuilder)
264
265 if (result === undefined || result === null) {
266 // Disabled query - return null
267 return null
268 }
269
270 return createLiveQueryCollection({
271 query: configOrQueryOrCollection,
272 startSync: true,
273 })
274 }
275
276 const innerCollection = configOrQueryOrCollection()
277
278 if (innerCollection === undefined || innerCollection === null) {
279 // Disabled query - return null
280 return null
281 }
282
283 if (innerCollection instanceof CollectionImpl) {
284 innerCollection.startSyncImmediate()
285 return innerCollection as Collection
286 }
287
288 return createLiveQueryCollection({
289 ...innerCollection,
290 startSync: true,
291 })
292 },
293 undefined,
294 { name: `TanstackDBCollectionMemo` },
295 )
296
297 // Reactive state that gets updated granularly through change events
298 const state = new ReactiveMap<string | number, any>()
299
300 // Reactive data array that maintains sorted order
301 const [data, setData] = createStore<Array<any>>([], {
302 name: `TanstackDBData`,
303 })
304
305 // Track collection status reactively
306 const [status, setStatus] = createSignal(
307 collection() ? collection()!.status : (`disabled` as const),
308 {
309 name: `TanstackDBStatus`,
310 },
311 )
312
313 // Helper to sync data array from collection in correct order
314 const syncDataFromCollection = (
315 currentCollection: Collection<any, any, any>,
316 ) => {
317 setData((prev) =>
318 reconcile(Array.from(currentCollection.values()))(prev).filter(Boolean),
319 )
320 }
321
322 const [getDataResource] = createResource(
323 () => ({ currentCollection: collection() }),
324 async ({ currentCollection }) => {
325 if (!currentCollection) {
326 return []
327 }
328 setStatus(currentCollection.status)
329 try {
330 await currentCollection.toArrayWhenReady()
331 } catch (error) {
332 setStatus(`error`)
333 throw error
334 }
335 // Initialize state with current collection data
336 batch(() => {
337 state.clear()
338 for (const [key, value] of currentCollection.entries()) {
339 state.set(key, value)
340 }
341 syncDataFromCollection(currentCollection)
342 setStatus(currentCollection.status)
343 })
344 return data
345 },
346 {
347 name: `TanstackDBData`,
348 deferStream: false,
349 initialValue: data,
350 },
351 )
352
353 createEffect(() => {
354 const currentCollection = collection()
355 if (!currentCollection) {
356 setStatus(`disabled` as const)
357 state.clear()
358 setData([])
359 return
360 }
361 const subscription = currentCollection.subscribeChanges(
362 (changes: Array<ChangeMessage<any>>) => {
363 // Apply each change individually to the reactive state
364 batch(() => {
365 for (const change of changes) {
366 switch (change.type) {
367 case `insert`:
368 case `update`:
369 state.set(change.key, change.value)
370 break
371 case `delete`:
372 state.delete(change.key)
373 break
374 }
375 }
376
377 syncDataFromCollection(currentCollection)
378
379 // Update status ref on every change
380 setStatus(currentCollection.status)
381 })
382 },
383 {
384 // Include initial state to ensure immediate population for pre-created collections
385 includeInitialState: true,
386 },
387 )
388
389 onCleanup(() => {
390 subscription.unsubscribe()
391 })
392 })
393
394 // We have to remove getters from the resource function so we wrap it
395 function getData() {
396 return getDataResource()
397 }
398
399 Object.defineProperties(getData, {
400 data: {
401 get() {
402 return getData()
403 },
404 },
405 status: {
406 get() {
407 return status()
408 },
409 },
410 collection: {
411 get() {
412 return collection()
413 },
414 },
415 state: {
416 get() {
417 return state
418 },
419 },
420 isLoading: {
421 get() {
422 return status() === `loading`
423 },
424 },
425 isReady: {
426 get() {
427 return status() === `ready` || status() === `disabled`
428 },
429 },
430 isIdle: {
431 get() {
432 return status() === `idle`
433 },
434 },
435 isError: {
436 get() {
437 return status() === `error`
438 },
439 },
440 isCleanedUp: {
441 get() {
442 return status() === `cleaned-up`
443 },
444 },
445 })
446 return getData
447}