Open History to see the last commit
1---
2id: useLiveQuery
3title: useLiveQuery
4---
5
6## Call Signature
7
8```ts
9function useLiveQuery<TContext>(queryFn, deps?): UseLiveQueryReturn<{ [K in string | number | symbol]: ResultValue<TContext>[K] }, InferResultType<TContext>>;
10```
11
12Defined in: [packages/svelte-db/src/useLiveQuery.svelte.ts:180](https://github.com/TanStack/db/blob/main/packages/svelte-db/src/useLiveQuery.svelte.ts#L180)
13
14Create a live query using a query function
15
16### Type Parameters
17
18#### TContext
19
20`TContext` *extends* `Context`
21
22### Parameters
23
24#### queryFn
25
26(`q`) => `QueryBuilder`\<`TContext`\>
27
28Query function that defines what data to fetch
29
30#### deps?
31
32() => `unknown`[]
33
34Array of reactive dependencies that trigger query re-execution when changed
35
36### Returns
37
38[`UseLiveQueryReturn`](../interfaces/UseLiveQueryReturn.md)\<\{ \[K in string \| number \| symbol\]: ResultValue\<TContext\>\[K\] \}, `InferResultType`\<`TContext`\>\>
39
40Reactive object with query data, state, and status information
41
42### Remarks
43
44**IMPORTANT - Destructuring in Svelte 5:**
45Direct destructuring breaks reactivity. To destructure, wrap with `$derived`:
46
47❌ **Incorrect** - Loses reactivity:
48```ts
49const { data, isLoading } = useLiveQuery(...)
50```
51
52✅ **Correct** - Maintains reactivity:
53```ts
54// Option 1: Use dot notation (recommended)
55const query = useLiveQuery(...)
56// Access: query.data, query.isLoading
57
58// Option 2: Wrap with $derived for destructuring
59const query = useLiveQuery(...)
60const { data, isLoading } = $derived(query)
61```
62
63This is a fundamental Svelte 5 limitation, not a library bug. See:
64https://github.com/sveltejs/svelte/issues/11002
65
66### Examples
67
68```ts
69// Basic query with object syntax (recommended pattern)
70const todosQuery = useLiveQuery((q) =>
71 q.from({ todos: todosCollection })
72 .where(({ todos }) => eq(todos.completed, false))
73 .select(({ todos }) => ({ id: todos.id, text: todos.text }))
74)
75// Access via: todosQuery.data, todosQuery.isLoading, etc.
76```
77
78```ts
79// With reactive dependencies
80let minPriority = $state(5)
81const todosQuery = useLiveQuery(
82 (q) => q.from({ todos: todosCollection })
83 .where(({ todos }) => gt(todos.priority, minPriority)),
84 [() => minPriority] // Re-run when minPriority changes
85)
86```
87
88```ts
89// Destructuring with $derived (if needed)
90const query = useLiveQuery((q) =>
91 q.from({ todos: todosCollection })
92)
93const { data, isLoading, isError } = $derived(query)
94// Now data, isLoading, and isError maintain reactivity
95```
96
97```ts
98// Join pattern
99const issuesQuery = useLiveQuery((q) =>
100 q.from({ issues: issueCollection })
101 .join({ persons: personCollection }, ({ issues, persons }) =>
102 eq(issues.userId, persons.id)
103 )
104 .select(({ issues, persons }) => ({
105 id: issues.id,
106 title: issues.title,
107 userName: persons.name
108 }))
109)
110```
111
112```ts
113// Handle loading and error states in template
114const todosQuery = useLiveQuery((q) =>
115 q.from({ todos: todoCollection })
116)
117
118// In template:
119// {#if todosQuery.isLoading}
120// <div>Loading...</div>
121// {:else if todosQuery.isError}
122// <div>Error: {todosQuery.status}</div>
123// {:else}
124// <ul>
125// {#each todosQuery.data as todo (todo.id)}
126// <li>{todo.text}</li>
127// {/each}
128// </ul>
129// {/if}
130```
131
132## Call Signature
133
134```ts
135function useLiveQuery<TContext>(queryFn, deps?): UseLiveQueryReturn<{ [K in string | number | symbol]: ResultValue<TContext>[K] }, InferResultType<TContext> | undefined>;
136```
137
138Defined in: [packages/svelte-db/src/useLiveQuery.svelte.ts:186](https://github.com/TanStack/db/blob/main/packages/svelte-db/src/useLiveQuery.svelte.ts#L186)
139
140Create a live query using a query function
141
142### Type Parameters
143
144#### TContext
145
146`TContext` *extends* `Context`
147
148### Parameters
149
150#### queryFn
151
152(`q`) => `QueryBuilder`\<`TContext`\> \| `null` \| `undefined`
153
154Query function that defines what data to fetch
155
156#### deps?
157
158() => `unknown`[]
159
160Array of reactive dependencies that trigger query re-execution when changed
161
162### Returns
163
164[`UseLiveQueryReturn`](../interfaces/UseLiveQueryReturn.md)\<\{ \[K in string \| number \| symbol\]: ResultValue\<TContext\>\[K\] \}, `InferResultType`\<`TContext`\> \| `undefined`\>
165
166Reactive object with query data, state, and status information
167
168### Remarks
169
170**IMPORTANT - Destructuring in Svelte 5:**
171Direct destructuring breaks reactivity. To destructure, wrap with `$derived`:
172
173❌ **Incorrect** - Loses reactivity:
174```ts
175const { data, isLoading } = useLiveQuery(...)
176```
177
178✅ **Correct** - Maintains reactivity:
179```ts
180// Option 1: Use dot notation (recommended)
181const query = useLiveQuery(...)
182// Access: query.data, query.isLoading
183
184// Option 2: Wrap with $derived for destructuring
185const query = useLiveQuery(...)
186const { data, isLoading } = $derived(query)
187```
188
189This is a fundamental Svelte 5 limitation, not a library bug. See:
190https://github.com/sveltejs/svelte/issues/11002
191
192### Examples
193
194```ts
195// Basic query with object syntax (recommended pattern)
196const todosQuery = useLiveQuery((q) =>
197 q.from({ todos: todosCollection })
198 .where(({ todos }) => eq(todos.completed, false))
199 .select(({ todos }) => ({ id: todos.id, text: todos.text }))
200)
201// Access via: todosQuery.data, todosQuery.isLoading, etc.
202```
203
204```ts
205// With reactive dependencies
206let minPriority = $state(5)
207const todosQuery = useLiveQuery(
208 (q) => q.from({ todos: todosCollection })
209 .where(({ todos }) => gt(todos.priority, minPriority)),
210 [() => minPriority] // Re-run when minPriority changes
211)
212```
213
214```ts
215// Destructuring with $derived (if needed)
216const query = useLiveQuery((q) =>
217 q.from({ todos: todosCollection })
218)
219const { data, isLoading, isError } = $derived(query)
220// Now data, isLoading, and isError maintain reactivity
221```
222
223```ts
224// Join pattern
225const issuesQuery = useLiveQuery((q) =>
226 q.from({ issues: issueCollection })
227 .join({ persons: personCollection }, ({ issues, persons }) =>
228 eq(issues.userId, persons.id)
229 )
230 .select(({ issues, persons }) => ({
231 id: issues.id,
232 title: issues.title,
233 userName: persons.name
234 }))
235)
236```
237
238```ts
239// Handle loading and error states in template
240const todosQuery = useLiveQuery((q) =>
241 q.from({ todos: todoCollection })
242)
243
244// In template:
245// {#if todosQuery.isLoading}
246// <div>Loading...</div>
247// {:else if todosQuery.isError}
248// <div>Error: {todosQuery.status}</div>
249// {:else}
250// <ul>
251// {#each todosQuery.data as todo (todo.id)}
252// <li>{todo.text}</li>
253// {/each}
254// </ul>
255// {/if}
256```
257
258## Call Signature
259
260```ts
261function useLiveQuery<TContext>(config, deps?): UseLiveQueryReturn<{ [K in string | number | symbol]: ResultValue<TContext>[K] }, InferResultType<TContext>>;
262```
263
264Defined in: [packages/svelte-db/src/useLiveQuery.svelte.ts:234](https://github.com/TanStack/db/blob/main/packages/svelte-db/src/useLiveQuery.svelte.ts#L234)
265
266Create a live query using configuration object
267
268### Type Parameters
269
270#### TContext
271
272`TContext` *extends* `Context`
273
274### Parameters
275
276#### config
277
278[`UseLiveQueryConfig`](../type-aliases/UseLiveQueryConfig.md)\<`TContext`\>
279
280Configuration object with query and options
281
282#### deps?
283
284() => `unknown`[]
285
286Array of reactive dependencies that trigger query re-execution when changed
287
288### Returns
289
290[`UseLiveQueryReturn`](../interfaces/UseLiveQueryReturn.md)\<\{ \[K in string \| number \| symbol\]: ResultValue\<TContext\>\[K\] \}, `InferResultType`\<`TContext`\>\>
291
292Reactive object with query data, state, and status information
293
294### Examples
295
296```ts
297// Basic config object usage
298const todosQuery = useLiveQuery({
299 query: (q) => q.from({ todos: todosCollection }),
300 gcTime: 60000
301})
302```
303
304```ts
305// With reactive dependencies
306let filter = $state('active')
307const todosQuery = useLiveQuery({
308 query: (q) => q.from({ todos: todosCollection })
309 .where(({ todos }) => eq(todos.status, filter))
310}, [() => filter])
311```
312
313```ts
314// Handle all states uniformly
315const itemsQuery = useLiveQuery({
316 query: (q) => q.from({ items: itemCollection })
317})
318
319// In template:
320// {#if itemsQuery.isLoading}
321// <div>Loading...</div>
322// {:else if itemsQuery.isError}
323// <div>Something went wrong</div>
324// {:else if !itemsQuery.isReady}
325// <div>Preparing...</div>
326// {:else}
327// <div>{itemsQuery.data.length} items loaded</div>
328// {/if}
329```
330
331## Call Signature
332
333```ts
334function useLiveQuery<TResult, TKey, TUtils>(liveQueryCollection): UseLiveQueryReturnWithCollection<TResult, TKey, TUtils, TResult[]>;
335```
336
337Defined in: [packages/svelte-db/src/useLiveQuery.svelte.ts:283](https://github.com/TanStack/db/blob/main/packages/svelte-db/src/useLiveQuery.svelte.ts#L283)
338
339Subscribe to an existing query collection (can be reactive)
340
341### Type Parameters
342
343#### TResult
344
345`TResult` *extends* `object`
346
347#### TKey
348
349`TKey` *extends* `string` \| `number`
350
351#### TUtils
352
353`TUtils` *extends* `Record`\<`string`, `any`\>
354
355### Parameters
356
357#### liveQueryCollection
358
359`MaybeGetter`\<`Collection`\<`TResult`, `TKey`, `TUtils`, `StandardSchemaV1`\<`unknown`, `unknown`\>, `TResult`\> & `NonSingleResult`\>
360
361Pre-created query collection to subscribe to (can be a getter)
362
363### Returns
364
365[`UseLiveQueryReturnWithCollection`](../interfaces/UseLiveQueryReturnWithCollection.md)\<`TResult`, `TKey`, `TUtils`, `TResult`[]\>
366
367Reactive object with query data, state, and status information
368
369### Examples
370
371```ts
372// Using pre-created query collection
373const myLiveQuery = createLiveQueryCollection((q) =>
374 q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
375)
376const queryResult = useLiveQuery(myLiveQuery)
377```
378
379```ts
380// Reactive query collection reference
381let selectedQuery = $state(todosQuery)
382const queryResult = useLiveQuery(() => selectedQuery)
383
384// Switch queries reactively
385selectedQuery = archiveQuery
386```
387
388```ts
389// Access query collection methods directly
390const queryResult = useLiveQuery(existingQuery)
391
392// Use underlying collection for mutations
393const handleToggle = (id) => {
394 queryResult.collection.update(id, draft => { draft.completed = !draft.completed })
395}
396```
397
398```ts
399// Handle states consistently
400const queryResult = useLiveQuery(sharedQuery)
401
402// In template:
403// {#if queryResult.isLoading}
404// <div>Loading...</div>
405// {:else if queryResult.isError}
406// <div>Error loading data</div>
407// {:else}
408// {#each queryResult.data as item (item.id)}
409// <Item {...item} />
410// {/each}
411// {/if}
412```
413
414## Call Signature
415
416```ts
417function useLiveQuery<TResult, TKey, TUtils>(liveQueryCollection): UseLiveQueryReturnWithCollection<TResult, TKey, TUtils, TResult | undefined>;
418```
419
420Defined in: [packages/svelte-db/src/useLiveQuery.svelte.ts:294](https://github.com/TanStack/db/blob/main/packages/svelte-db/src/useLiveQuery.svelte.ts#L294)
421
422Create a live query using a query function
423
424### Type Parameters
425
426#### TResult
427
428`TResult` *extends* `object`
429
430#### TKey
431
432`TKey` *extends* `string` \| `number`
433
434#### TUtils
435
436`TUtils` *extends* `Record`\<`string`, `any`\>
437
438### Parameters
439
440#### liveQueryCollection
441
442`MaybeGetter`\<`Collection`\<`TResult`, `TKey`, `TUtils`, `StandardSchemaV1`\<`unknown`, `unknown`\>, `TResult`\> & `SingleResult`\>
443
444### Returns
445
446[`UseLiveQueryReturnWithCollection`](../interfaces/UseLiveQueryReturnWithCollection.md)\<`TResult`, `TKey`, `TUtils`, `TResult` \| `undefined`\>
447
448Reactive object with query data, state, and status information
449
450### Remarks
451
452**IMPORTANT - Destructuring in Svelte 5:**
453Direct destructuring breaks reactivity. To destructure, wrap with `$derived`:
454
455❌ **Incorrect** - Loses reactivity:
456```ts
457const { data, isLoading } = useLiveQuery(...)
458```
459
460✅ **Correct** - Maintains reactivity:
461```ts
462// Option 1: Use dot notation (recommended)
463const query = useLiveQuery(...)
464// Access: query.data, query.isLoading
465
466// Option 2: Wrap with $derived for destructuring
467const query = useLiveQuery(...)
468const { data, isLoading } = $derived(query)
469```
470
471This is a fundamental Svelte 5 limitation, not a library bug. See:
472https://github.com/sveltejs/svelte/issues/11002
473
474### Examples
475
476```ts
477// Basic query with object syntax (recommended pattern)
478const todosQuery = useLiveQuery((q) =>
479 q.from({ todos: todosCollection })
480 .where(({ todos }) => eq(todos.completed, false))
481 .select(({ todos }) => ({ id: todos.id, text: todos.text }))
482)
483// Access via: todosQuery.data, todosQuery.isLoading, etc.
484```
485
486```ts
487// With reactive dependencies
488let minPriority = $state(5)
489const todosQuery = useLiveQuery(
490 (q) => q.from({ todos: todosCollection })
491 .where(({ todos }) => gt(todos.priority, minPriority)),
492 [() => minPriority] // Re-run when minPriority changes
493)
494```
495
496```ts
497// Destructuring with $derived (if needed)
498const query = useLiveQuery((q) =>
499 q.from({ todos: todosCollection })
500)
501const { data, isLoading, isError } = $derived(query)
502// Now data, isLoading, and isError maintain reactivity
503```
504
505```ts
506// Join pattern
507const issuesQuery = useLiveQuery((q) =>
508 q.from({ issues: issueCollection })
509 .join({ persons: personCollection }, ({ issues, persons }) =>
510 eq(issues.userId, persons.id)
511 )
512 .select(({ issues, persons }) => ({
513 id: issues.id,
514 title: issues.title,
515 userName: persons.name
516 }))
517)
518```
519
520```ts
521// Handle loading and error states in template
522const todosQuery = useLiveQuery((q) =>
523 q.from({ todos: todoCollection })
524)
525
526// In template:
527// {#if todosQuery.isLoading}
528// <div>Loading...</div>
529// {:else if todosQuery.isError}
530// <div>Error: {todosQuery.status}</div>
531// {:else}
532// <ul>
533// {#each todosQuery.data as todo (todo.id)}
534// <li>{todo.text}</li>
535// {/each}
536// </ul>
537// {/if}
538```