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

useLiveQuery.svelte.ts

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