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

useLiveQuery.svelte.ts

400 lines11.8 KB

1import { flushSync, untrack } from "svelte"
2import { createLiveQueryCollection } from "@tanstack/db"
3import { SvelteMap } from "svelte/reactivity"
4import type {
5 ChangeMessage,
6 Collection,
7 CollectionStatus,
8 Context,
9 GetResult,
10 InitialQueryBuilder,
11 LiveQueryCollectionConfig,
12 QueryBuilder,
13} from "@tanstack/db"
14​
15/**
16 * Return type for useLiveQuery hook
17 * @property state - Reactive Map of query results (key → item)
18 * @property data - Reactive array of query results in order
19 * @property collection - The underlying query collection instance
20 * @property status - Current query status
21 * @property isLoading - True while initial query data is loading
22 * @property isReady - True when query has received first data and is ready
23 * @property isIdle - True when query hasn't started yet
24 * @property isError - True when query encountered an error
25 * @property isCleanedUp - True when query has been cleaned up
26 */
27export interface UseLiveQueryReturn<T extends object> {
28 state: Map<string | number, T>
29 data: Array<T>
30 collection: Collection<T, string | number, {}>
31 status: CollectionStatus
32 isLoading: boolean
33 isReady: boolean
34 isIdle: boolean
35 isError: boolean
36 isCleanedUp: boolean
38​
39export interface UseLiveQueryReturnWithCollection<
40 T extends object,
41 TKey extends string | number,
42 TUtils extends Record<string, any>,
43> {
44 state: Map<TKey, T>
45 data: Array<T>
46 collection: Collection<T, TKey, TUtils>
47 status: CollectionStatus
48 isLoading: boolean
49 isReady: boolean
50 isIdle: boolean
51 isError: boolean
52 isCleanedUp: boolean
54​
55type MaybeGetter<T> = T | (() => T)
56​
57function toValue<T>(value: MaybeGetter<T>): T {
58 if (typeof value === `function`) {
59 return (value as () => T)()
60 }
61 return value
63​
64/**
65 * Create a live query using a query function
66 * @param queryFn - Query function that defines what data to fetch
67 * @param deps - Array of reactive dependencies that trigger query re-execution when changed
68 * @returns Reactive object with query data, state, and status information
69 * @example
70 * // Basic query with object syntax
71 * const todosQuery = useLiveQuery((q) =>
72 * q.from({ todos: todosCollection })
73 * .where(({ todos }) => eq(todos.completed, false))
74 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
75 * )
76 *
77 * @example
78 * // With reactive dependencies
79 * let minPriority = $state(5)
80 * const todosQuery = useLiveQuery(
81 * (q) => q.from({ todos: todosCollection })
82 * .where(({ todos }) => gt(todos.priority, minPriority)),
83 * [() => minPriority] // Re-run when minPriority changes
84 * )
85 *
86 * @example
87 * // Join pattern
88 * const issuesQuery = useLiveQuery((q) =>
89 * q.from({ issues: issueCollection })
90 * .join({ persons: personCollection }, ({ issues, persons }) =>
91 * eq(issues.userId, persons.id)
92 * )
93 * .select(({ issues, persons }) => ({
94 * id: issues.id,
95 * title: issues.title,
96 * userName: persons.name
97 * }))
98 * )
99 *
100 * @example
101 * // Handle loading and error states in template
102 * const todosQuery = useLiveQuery((q) =>
103 * q.from({ todos: todoCollection })
104 * )
105 *
106 * // In template:
107 * // {#if todosQuery.isLoading}
108 * // <div>Loading...</div>
109 * // {:else if todosQuery.isError}
110 * // <div>Error: {todosQuery.status}</div>
111 * // {:else}
112 * // <ul>
113 * // {#each todosQuery.data as todo (todo.id)}
114 * // <li>{todo.text}</li>
115 * // {/each}
116 * // </ul>
117 * // {/if}
118 */
119// Overload 1: Accept just the query function
120export function useLiveQuery<TContext extends Context>(
121 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
122 deps?: Array<() => unknown>
123): UseLiveQueryReturn<GetResult<TContext>>
124​
125/**
126 * Create a live query using configuration object
127 * @param config - Configuration object with query and options
128 * @param deps - Array of reactive dependencies that trigger query re-execution when changed
129 * @returns Reactive object with query data, state, and status information
130 * @example
131 * // Basic config object usage
132 * const todosQuery = useLiveQuery({
133 * query: (q) => q.from({ todos: todosCollection }),
134 * gcTime: 60000
135 * })
136 *
137 * @example
138 * // With reactive dependencies
139 * let filter = $state('active')
140 * const todosQuery = useLiveQuery({
141 * query: (q) => q.from({ todos: todosCollection })
142 * .where(({ todos }) => eq(todos.status, filter))
143 * }, [() => filter])
144 *
145 * @example
146 * // Handle all states uniformly
147 * const itemsQuery = useLiveQuery({
148 * query: (q) => q.from({ items: itemCollection })
149 * })
150 *
151 * // In template:
152 * // {#if itemsQuery.isLoading}
153 * // <div>Loading...</div>
154 * // {:else if itemsQuery.isError}
155 * // <div>Something went wrong</div>
156 * // {:else if !itemsQuery.isReady}
157 * // <div>Preparing...</div>
158 * // {:else}
159 * // <div>{itemsQuery.data.length} items loaded</div>
160 * // {/if}
161 */
162// Overload 2: Accept config object
163export function useLiveQuery<TContext extends Context>(
164 config: LiveQueryCollectionConfig<TContext>,
165 deps?: Array<() => unknown>
166): UseLiveQueryReturn<GetResult<TContext>>
167​
168/**
169 * Subscribe to an existing query collection (can be reactive)
170 * @param liveQueryCollection - Pre-created query collection to subscribe to (can be a getter)
171 * @returns Reactive object with query data, state, and status information
172 * @example
173 * // Using pre-created query collection
174 * const myLiveQuery = createLiveQueryCollection((q) =>
175 * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
176 * )
177 * const queryResult = useLiveQuery(myLiveQuery)
178 *
179 * @example
180 * // Reactive query collection reference
181 * let selectedQuery = $state(todosQuery)
182 * const queryResult = useLiveQuery(() => selectedQuery)
183 *
184 * // Switch queries reactively
185 * selectedQuery = archiveQuery
186 *
187 * @example
188 * // Access query collection methods directly
189 * const queryResult = useLiveQuery(existingQuery)
190 *
191 * // Use underlying collection for mutations
192 * const handleToggle = (id) => {
193 * queryResult.collection.update(id, draft => { draft.completed = !draft.completed })
194 * }
195 *
196 * @example
197 * // Handle states consistently
198 * const queryResult = useLiveQuery(sharedQuery)
199 *
200 * // In template:
201 * // {#if queryResult.isLoading}
202 * // <div>Loading...</div>
203 * // {:else if queryResult.isError}
204 * // <div>Error loading data</div>
205 * // {:else}
206 * // {#each queryResult.data as item (item.id)}
207 * // <Item {...item} />
208 * // {/each}
209 * // {/if}
210 */
211// Overload 3: Accept pre-created live query collection (can be reactive)
212export function useLiveQuery<
213 TResult extends object,
214 TKey extends string | number,
215 TUtils extends Record<string, any>,
216>(
217 liveQueryCollection: MaybeGetter<Collection<TResult, TKey, TUtils>>
218): UseLiveQueryReturnWithCollection<TResult, TKey, TUtils>
219​
220// Implementation
221export function useLiveQuery(
222 configOrQueryOrCollection: any,
223 deps: Array<() => unknown> = []
224): UseLiveQueryReturn<any> | UseLiveQueryReturnWithCollection<any, any, any> {
225 const collection = $derived.by(() => {
226 // First check if the original parameter might be a getter
227 // by seeing if toValue returns something different than the original
228 let unwrappedParam = configOrQueryOrCollection
229 try {
230 const potentiallyUnwrapped = toValue(configOrQueryOrCollection)
231 if (potentiallyUnwrapped !== configOrQueryOrCollection) {
232 unwrappedParam = potentiallyUnwrapped
233 }
234 } catch {
235 // If toValue fails, use original parameter
236 unwrappedParam = configOrQueryOrCollection
237 }
238​
239 // Check if it's already a collection by checking for specific collection methods
240 const isCollection =
241 unwrappedParam &&
242 typeof unwrappedParam === `object` &&
243 typeof unwrappedParam.subscribeChanges === `function` &&
244 typeof unwrappedParam.startSyncImmediate === `function` &&
245 typeof unwrappedParam.id === `string`
246​
247 if (isCollection) {
248 // It's already a collection, ensure sync is started for Svelte helpers
249 // Only start sync if the collection is in idle state
250 if (unwrappedParam.status === `idle`) {
251 unwrappedParam.startSyncImmediate()
252 }
253 return unwrappedParam
254 }
255​
256 // Reference deps to make computed reactive to them
257 deps.forEach((dep) => toValue(dep))
258​
259 // Ensure we always start sync for Svelte helpers
260 if (typeof unwrappedParam === `function`) {
261 return createLiveQueryCollection({
262 query: unwrappedParam,
263 startSync: true,
264 })
265 } else {
266 return createLiveQueryCollection({
267 ...unwrappedParam,
268 startSync: true,
269 })
270 }
271 })
272​
273 // Reactive state that gets updated granularly through change events
274 const state = new SvelteMap<string | number, any>()
275​
276 // Reactive data array that maintains sorted order
277 let internalData = $state<Array<any>>([])
278​
279 // Track collection status reactively
280 let status = $state(collection.status)
281​
282 // Helper to sync data array from collection in correct order
283 const syncDataFromCollection = (
284 currentCollection: Collection<any, any, any>
285 ) => {
286 untrack(() => {
287 internalData = []
288 internalData.push(...Array.from(currentCollection.values()))
289 })
290 }
291​
292 // Track current unsubscribe function
293 let currentUnsubscribe: (() => void) | null = null
294​
295 // Watch for collection changes and subscribe to updates
296 $effect(() => {
297 const currentCollection = collection
298​
299 // Update status state whenever the effect runs
300 status = currentCollection.status
301​
302 // Clean up previous subscription
303 if (currentUnsubscribe) {
304 currentUnsubscribe()
305 }
306​
307 // Initialize state with current collection data
308 untrack(() => {
309 state.clear()
310 for (const [key, value] of currentCollection.entries()) {
311 state.set(key, value)
312 }
313 })
314​
315 // Initialize data array in correct order
316 syncDataFromCollection(currentCollection)
317​
318 // Listen for the first ready event to catch status transitions
319 // that might not trigger change events (fixes async status transition bug)
320 currentCollection.onFirstReady(() => {
321 // Use flushSync to ensure Svelte reactivity updates properly
322 flushSync(() => {
323 status = currentCollection.status
324 })
325 })
326​
327 // Subscribe to collection changes with granular updates
328 const subscription = currentCollection.subscribeChanges(
329 (changes: Array<ChangeMessage<any>>) => {
330 // Apply each change individually to the reactive state
331 untrack(() => {
332 for (const change of changes) {
333 switch (change.type) {
334 case `insert`:
335 case `update`:
336 state.set(change.key, change.value)
337 break
338 case `delete`:
339 state.delete(change.key)
340 break
341 }
342 }
343 })
344​
345 // Update the data array to maintain sorted order
346 syncDataFromCollection(currentCollection)
347 // Update status state on every change
348 status = currentCollection.status
349 },
350 {
351 includeInitialState: true,
352 }
353 )
354​
355 currentUnsubscribe = subscription.unsubscribe.bind(subscription)
356​
357 // Preload collection data if not already started
358 if (currentCollection.status === `idle`) {
359 currentCollection.preload().catch(console.error)
360 }
361​
362 // Cleanup when effect is invalidated
363 return () => {
364 if (currentUnsubscribe) {
365 currentUnsubscribe()
366 currentUnsubscribe = null
367 }
368 }
369 })
370​
371 return {
372 get state() {
373 return state
374 },
375 get data() {
376 return internalData
377 },
378 get collection() {
379 return collection
380 },
381 get status() {
382 return status
383 },
384 get isLoading() {
385 return status === `loading` || status === `initialCommit`
386 },
387 get isReady() {
388 return status === `ready`
389 },
390 get isIdle() {
391 return status === `idle`
392 },
393 get isError() {
394 return status === `error`
395 },
396 get isCleanedUp() {
397 return status === `cleaned-up`
398 },
399 }