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

useLiveQuery.ts

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