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

useLiveQuery.svelte.ts

579 lines18.1 KB

1// eslint-disable-next-line import/no-duplicates -- See https://github.com/un-ts/eslint-plugin-import-x/issues/308
2import { untrack } from 'svelte'
3// eslint-disable-next-line import/no-duplicates -- See https://github.com/un-ts/eslint-plugin-import-x/issues/308
4import { SvelteMap } from 'svelte/reactivity'
5import {
6 BaseQueryBuilder,
7 UnhashableQueryIRError,
8 createLiveQueryObserver,
9 getLiveQueryHash,
10 getPublicCollection,
11 getStableValueHash,
12 isCollection,
13 isSingleResultCollection,
14 prepareLiveQueryValue,
15 resolveLiveQueryValue,
16 resumeDeferredLiveQueryCollections,
17} from '@tanstack/db'
18import { useOptionalDbClient } from './db-context.js'
19import type {
20 ChangeMessage,
21 Collection,
22 CollectionStatus,
23 Context,
24 DbClient,
25 DeferredLiveQueryCollections,
26 GetResult,
27 InferResultType,
28 InitialQueryBuilder,
29 LiveQueryCollectionConfig,
30 LiveQueryKey,
31 LiveQueryObserver,
32 LiveQueryPersistedStatus,
33 NonSingleResult,
34 QueryBuilder,
35 SingleResult,
36} from '@tanstack/db'
37​
38const DEFAULT_GC_TIME_MS = 1
39​
40/** Copy a snapshot's ordered rows; a single-result query's `data` is one row. */
41function snapshotRows(data: unknown): Array<any> {
42 if (Array.isArray(data)) return [...data]
43 return data === undefined ? [] : [data]
45​
46/**
47 * Return type for useLiveQuery hook
48 * @property state - Reactive Map of query results (key → item)
49 * @property data - Reactive array of query results in order, or single item when using findOne()
50 * @property collection - The underlying query collection instance
51 * @property status - Current query status
52 * @property isLoading - True while initial query data is loading
53 * @property isReady - True when query has received first data and is ready
54 * @property isIdle - True when query hasn't started yet
55 * @property isError - True when query encountered an error
56 * @property isCleanedUp - True when query has been cleaned up
57 */
58export interface UseLiveQueryReturn<T extends object, TData = Array<T>> {
59 state: Map<string | number, T>
60 data: TData
61 collection: Collection<T, string | number, {}>
62 status: CollectionStatus
63 isLoading: boolean
64 isReady: boolean
65 persistedStatus: LiveQueryPersistedStatus
66 isPersistedReady: boolean
67 persistedError: unknown | undefined
68 isIdle: boolean
69 isError: boolean
70 isCleanedUp: boolean
72​
73type InferConditionalResultType<TContext extends Context> =
74 TContext extends SingleResult
75 ? InferResultType<TContext> | []
76 : InferResultType<TContext>
77​
78export type ConditionalUseLiveQueryReturn<
79 T extends object,
80 TData = Array<T>,
81> = Omit<UseLiveQueryReturn<T, TData>, `collection` | `status`> & {
82 collection: Collection<T, string | number, {}> | null
83 status: CollectionStatus | `disabled`
85​
86export interface UseLiveQueryReturnWithCollection<
87 T extends object,
88 TKey extends string | number,
89 TUtils extends Record<string, any>,
90 TData = Array<T>,
91> {
92 state: Map<TKey, T>
93 data: TData
94 collection: Collection<T, TKey, TUtils>
95 status: CollectionStatus
96 isLoading: boolean
97 isReady: boolean
98 persistedStatus: LiveQueryPersistedStatus
99 isPersistedReady: boolean
100 persistedError: unknown | undefined
101 isIdle: boolean
102 isError: boolean
103 isCleanedUp: boolean
105​
106type MaybeGetter<T> = T | (() => T)
107​
108export type UseLiveQueryConfig<TContext extends Context> =
109 LiveQueryCollectionConfig<TContext> & {
110 queryKey?: MaybeGetter<LiveQueryKey>
111 client?: DbClient
112 }
113​
114function toValue<T>(value: MaybeGetter<T>): T {
115 if (typeof value === `function`) {
116 return (value as () => T)()
117 }
118 return value
120​
121/**
122 * Create a live query using a query function
123 * @param queryFn - Query function that defines what data to fetch
124 * @param deps - Array of reactive dependencies that trigger query re-execution when changed
125 * @returns Reactive object with query data, state, and status information
126 *
127 * @remarks
128 * **IMPORTANT - Destructuring in Svelte 5:**
129 * Direct destructuring breaks reactivity. To destructure, wrap with `$derived`:
130 *
131 * ❌ **Incorrect** - Loses reactivity:
132 * ```ts
133 * const { data, isLoading } = useLiveQuery(...)
134 * ```
135 *
136 * ✅ **Correct** - Maintains reactivity:
137 * ```ts
138 * // Option 1: Use dot notation (recommended)
139 * const query = useLiveQuery(...)
140 * // Access: query.data, query.isLoading
141 *
142 * // Option 2: Wrap with $derived for destructuring
143 * const query = useLiveQuery(...)
144 * const { data, isLoading } = $derived(query)
145 * ```
146 *
147 * This is a fundamental Svelte 5 limitation, not a library bug. See:
148 * https://github.com/sveltejs/svelte/issues/11002
149 *
150 * @example
151 * // Basic query with object syntax (recommended pattern)
152 * const todosQuery = useLiveQuery((q) =>
153 * q.from({ todos: todosCollection })
154 * .where(({ todos }) => eq(todos.completed, false))
155 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
156 * )
157 * // Access via: todosQuery.data, todosQuery.isLoading, etc.
158 *
159 * @example
160 * // With reactive dependencies
161 * let minPriority = $state(5)
162 * const todosQuery = useLiveQuery(
163 * (q) => q.from({ todos: todosCollection })
164 * .where(({ todos }) => gt(todos.priority, minPriority)),
165 * [() => minPriority] // Re-run when minPriority changes
166 * )
167 *
168 * @example
169 * // Destructuring with $derived (if needed)
170 * const query = useLiveQuery((q) =>
171 * q.from({ todos: todosCollection })
172 * )
173 * const { data, isLoading, isError } = $derived(query)
174 * // Now data, isLoading, and isError maintain reactivity
175 *
176 * @example
177 * // Join pattern
178 * const issuesQuery = useLiveQuery((q) =>
179 * q.from({ issues: issueCollection })
180 * .join({ persons: personCollection }, ({ issues, persons }) =>
181 * eq(issues.userId, persons.id)
182 * )
183 * .select(({ issues, persons }) => ({
184 * id: issues.id,
185 * title: issues.title,
186 * userName: persons.name
187 * }))
188 * )
189 *
190 * @example
191 * // Handle loading and error states in template
192 * const todosQuery = useLiveQuery((q) =>
193 * q.from({ todos: todoCollection })
194 * )
195 *
196 * // In template:
197 * // {#if todosQuery.isLoading}
198 * // <div>Loading...</div>
199 * // {:else if todosQuery.isError}
200 * // <div>Error: {todosQuery.status}</div>
201 * // {:else}
202 * // <ul>
203 * // {#each todosQuery.data as todo (todo.id)}
204 * // <li>{todo.text}</li>
205 * // {/each}
206 * // </ul>
207 * // {/if}
208 */
209// Overload 1: Accept query function that always returns QueryBuilder
210export function useLiveQuery<TContext extends Context>(
211 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
212 deps?: Array<() => unknown>,
213): UseLiveQueryReturn<GetResult<TContext>, InferResultType<TContext>>
214​
215// Overload 1b: Accept query function that can return undefined/null
216export function useLiveQuery<TContext extends Context>(
217 queryFn: (
218 q: InitialQueryBuilder,
219 ) => QueryBuilder<TContext> | undefined | null,
220 deps?: Array<() => unknown>,
221): ConditionalUseLiveQueryReturn<
222 GetResult<TContext>,
223 InferConditionalResultType<TContext>
225​
226/**
227 * Create a live query using configuration object
228 * @param config - Configuration object with query and options
229 * @param deps - Array of reactive dependencies that trigger query re-execution when changed
230 * @returns Reactive object with query data, state, and status information
231 * @example
232 * // Basic config object usage
233 * const todosQuery = useLiveQuery({
234 * query: (q) => q.from({ todos: todosCollection }),
235 * gcTime: 60000
236 * })
237 *
238 * @example
239 * // With reactive dependencies
240 * let filter = $state('active')
241 * const todosQuery = useLiveQuery({
242 * query: (q) => q.from({ todos: todosCollection })
243 * .where(({ todos }) => eq(todos.status, filter))
244 * }, [() => filter])
245 *
246 * @example
247 * // Handle all states uniformly
248 * const itemsQuery = useLiveQuery({
249 * query: (q) => q.from({ items: itemCollection })
250 * })
251 *
252 * // In template:
253 * // {#if itemsQuery.isLoading}
254 * // <div>Loading...</div>
255 * // {:else if itemsQuery.isError}
256 * // <div>Something went wrong</div>
257 * // {:else if !itemsQuery.isReady}
258 * // <div>Preparing...</div>
259 * // {:else}
260 * // <div>{itemsQuery.data.length} items loaded</div>
261 * // {/if}
262 */
263// Overload 2: Accept config object
264export function useLiveQuery<TContext extends Context>(
265 config: UseLiveQueryConfig<TContext>,
266 deps?: Array<() => unknown>,
267): UseLiveQueryReturn<GetResult<TContext>, InferResultType<TContext>>
268​
269/**
270 * Subscribe to an existing query collection (can be reactive)
271 * @param liveQueryCollection - Pre-created query collection to subscribe to (can be a getter)
272 * @returns Reactive object with query data, state, and status information
273 * @example
274 * // Using pre-created query collection
275 * const myLiveQuery = createLiveQueryCollection((q) =>
276 * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
277 * )
278 * const queryResult = useLiveQuery(myLiveQuery)
279 *
280 * @example
281 * // Reactive query collection reference
282 * let selectedQuery = $state(todosQuery)
283 * const queryResult = useLiveQuery(() => selectedQuery)
284 *
285 * // Switch queries reactively
286 * selectedQuery = archiveQuery
287 *
288 * @example
289 * // Access query collection methods directly
290 * const queryResult = useLiveQuery(existingQuery)
291 *
292 * // Use underlying collection for mutations
293 * const handleToggle = (id) => {
294 * queryResult.collection.update(id, draft => { draft.completed = !draft.completed })
295 * }
296 *
297 * @example
298 * // Handle states consistently
299 * const queryResult = useLiveQuery(sharedQuery)
300 *
301 * // In template:
302 * // {#if queryResult.isLoading}
303 * // <div>Loading...</div>
304 * // {:else if queryResult.isError}
305 * // <div>Error loading data</div>
306 * // {:else}
307 * // {#each queryResult.data as item (item.id)}
308 * // <Item {...item} />
309 * // {/each}
310 * // {/if}
311 */
312// Overload 3: Accept pre-created live query collection WITHOUT SingleResult (returns array)
313export function useLiveQuery<
314 TResult extends object,
315 TKey extends string | number,
316 TUtils extends Record<string, any>,
317>(
318 liveQueryCollection: MaybeGetter<
319 Collection<TResult, TKey, TUtils> & NonSingleResult
320 >,
321): UseLiveQueryReturnWithCollection<TResult, TKey, TUtils, Array<TResult>>
322​
323// Overload 4: Accept pre-created live query collection WITH SingleResult (returns single item)
324export function useLiveQuery<
325 TResult extends object,
326 TKey extends string | number,
327 TUtils extends Record<string, any>,
328>(
329 liveQueryCollection: MaybeGetter<
330 Collection<TResult, TKey, TUtils> & SingleResult
331 >,
332): UseLiveQueryReturnWithCollection<TResult, TKey, TUtils, TResult | undefined>
333​
334// Implementation
335export function useLiveQuery(
336 configOrQueryOrCollection: any,
337 deps: Array<() => unknown> = [],
338): UseLiveQueryReturn<any> | UseLiveQueryReturnWithCollection<any, any, any> {
339 const contextDbClient = useOptionalDbClient()
340​
341 const resolved = $derived.by(() => {
342 // First check if the original parameter might be a getter
343 // by seeing if toValue returns something different than the original
344 let unwrappedParam = configOrQueryOrCollection
345 try {
346 const potentiallyUnwrapped = toValue(configOrQueryOrCollection)
347 if (potentiallyUnwrapped !== configOrQueryOrCollection) {
348 unwrappedParam = potentiallyUnwrapped
349 }
350 } catch {
351 // If toValue fails, use original parameter
352 unwrappedParam = configOrQueryOrCollection
353 }
354​
355 // Check if it's already a collection by checking for specific collection methods
356 const inputIsCollection = isCollection(unwrappedParam)
357 const dbClient = inputIsCollection
358 ? contextDbClient
359 : ((unwrappedParam as { client?: DbClient } | null)?.client ??
360 contextDbClient)
361​
362 if (inputIsCollection) {
363 // Warn when passing a collection directly with on-demand sync mode
364 // In on-demand mode, data is only loaded when queries with predicates request it
365 // Passing the collection directly doesn't provide any predicates, so no data loads
366 const syncMode = (unwrappedParam as { config?: { syncMode?: string } })
367 .config?.syncMode
368 if (syncMode === `on-demand`) {
369 console.warn(
370 `[useLiveQuery] Warning: Passing a collection with syncMode "on-demand" directly to useLiveQuery ` +
371 `will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.\n\n` +
372 `Instead, use a query builder function:\n` +
373 ` const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c))\n\n` +
374 `Or switch to syncMode "eager" if you want all data to sync automatically.`,
375 )
376 }
377 // It's already a collection, ensure sync is started for Svelte helpers
378 // Only start sync if the collection is in idle state
379 if (unwrappedParam.status === `idle`) {
380 unwrappedParam.startSyncImmediate()
381 }
382 return {
383 collection: unwrappedParam,
384 client: dbClient,
385 queryHash: getStableValueHash(
386 [`collection`, unwrappedParam.id],
387 `queryKey`,
388 ),
389 resumeDeferredCollections: () => {},
390 }
391 }
392​
393 // Reference deps to make computed reactive to them
394 const dependencyValues = deps.map((dep) => toValue(dep))
395 const deferredCollections: DeferredLiveQueryCollections = new Set()
396 const preparedValue = prepareLiveQueryValue(
397 unwrappedParam,
398 dbClient,
399 deferredCollections,
400 )
401 const configuredQueryKey = (
402 unwrappedParam as { queryKey?: MaybeGetter<LiveQueryKey> } | null
403 )?.queryKey
404 const queryKey = configuredQueryKey
405 ? toValue(configuredQueryKey)
406 : undefined
407​
408 let queryHash: string | undefined
409 try {
410 queryHash =
411 deps.length > 0 && !queryKey
412 ? getStableValueHash(
413 [`deps`, dependencyValues, getLiveQueryHash(preparedValue)],
414 `queryKey`,
415 )
416 : getLiveQueryHash(preparedValue, queryKey)
417 } catch (error) {
418 if (!(error instanceof UnhashableQueryIRError)) throw error
419 if (queryKey !== undefined) throw error
420 }
421​
422 let collection: Collection<any, any, any> | null
423 if (preparedValue === undefined || preparedValue === null) {
424 collection = null
425 } else if (isCollection(preparedValue)) {
426 collection = preparedValue
427 } else if (preparedValue instanceof BaseQueryBuilder) {
428 // Hydration keys the live-query Collection by identity.
429 collection = resolveLiveQueryValue(preparedValue, {
430 gcTime: DEFAULT_GC_TIME_MS,
431 pool: !dbClient,
432 })
433 } else {
434 collection = resolveLiveQueryValue(preparedValue, {
435 gcTime: DEFAULT_GC_TIME_MS,
436 pool: !dbClient,
437 })
438 }
439​
440 return {
441 collection,
442 client: dbClient,
443 queryHash,
444 resumeDeferredCollections: () =>
445 resumeDeferredLiveQueryCollections(deferredCollections),
446 }
447 })
448​
449 let currentResolved = untrack(() => resolved)
450 let currentObserver = createLiveQueryObserver(currentResolved.collection, {
451 client: currentResolved.client,
452 queryHash: currentResolved.queryHash,
453 onPreload: currentResolved.resumeDeferredCollections,
454 })
455 const initialSnapshot = currentObserver.getServerSnapshot()
456​
457 // Reactive state that gets updated granularly through change events
458 const state = new SvelteMap<string | number, any>(initialSnapshot.state ?? [])
459​
460 // Reactive data array that maintains sorted order
461 let internalData = $state<Array<any>>(snapshotRows(initialSnapshot.data))
462​
463 // Track collection status reactively
464 let status = $state(initialSnapshot.status)
465 let persistedStatus = $state(initialSnapshot.persistedStatus)
466 let persistedError = $state.raw<unknown>(initialSnapshot.persistedError)
467​
468 const syncFromObserver = (
469 observer: LiveQueryObserver<any, any>,
470 changes?: Array<ChangeMessage<any>>,
471 ) => {
472 const snapshot = observer.getSnapshot()
473 status = snapshot.status as CollectionStatus
474 persistedStatus = snapshot.persistedStatus
475 persistedError = snapshot.persistedError
476 untrack(() => {
477 if (changes && changes.length > 0) {
478 for (const change of changes) {
479 switch (change.type) {
480 case `insert`:
481 case `update`:
482 state.set(change.key, change.value)
483 break
484 case `delete`:
485 state.delete(change.key)
486 break
487 }
488 }
489 } else {
490 state.clear()
491 for (const [key, value] of snapshot.state ?? []) {
492 state.set(key, value)
493 }
494 }
495 internalData = snapshotRows(snapshot.data)
496 })
497 }
498​
499 // Watch for collection changes and subscribe to updates
500 $effect(() => {
501 const nextResolved = resolved
502​
503 if (nextResolved !== currentResolved) {
504 currentObserver.dispose()
505 currentResolved = nextResolved
506 currentObserver = createLiveQueryObserver(nextResolved.collection, {
507 client: nextResolved.client,
508 queryHash: nextResolved.queryHash,
509 onPreload: nextResolved.resumeDeferredCollections,
510 })
511 syncFromObserver(currentObserver)
512 }
513​
514 const observer = currentObserver
515​
516 const unsubscribe = observer.subscribe(
517 (changes: Array<ChangeMessage<any>> | undefined) => {
518 syncFromObserver(observer, changes)
519 },
520 )
521 try {
522 currentResolved.resumeDeferredCollections()
523 syncFromObserver(observer)
524 } catch (error) {
525 unsubscribe()
526 observer.dispose()
527 throw error
528 }
529​
530 // Cleanup when effect is invalidated
531 return () => {
532 unsubscribe()
533 if (observer === currentObserver) observer.dispose()
534 }
535 })
536​
537 return {
538 get state() {
539 return state
540 },
541 get data() {
542 const currentCollection = resolved.collection
543 if (currentCollection && isSingleResultCollection(currentCollection)) {
544 return internalData[0]
545 }
546 return internalData
547 },
548 get collection() {
549 return getPublicCollection(resolved.collection)
550 },
551 get status() {
552 return status as CollectionStatus
553 },
554 get isLoading() {
555 return status === `loading`
556 },
557 get isReady() {
558 return status === `ready` || status === `disabled`
559 },
560 get persistedStatus() {
561 return persistedStatus
562 },
563 get isPersistedReady() {
564 return persistedStatus === `ready`
565 },
566 get persistedError() {
567 return persistedError
568 },
569 get isIdle() {
570 return status === `idle`
571 },
572 get isError() {
573 return status === `error`
574 },
575 get isCleanedUp() {
576 return status === `cleaned-up`
577 },
578 }