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

useLiveQuery.svelte.ts

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