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

useLiveQuery.svelte.ts

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