Open History to see the last commit
1---
2title: TanStack DB Svelte Adapter
3id: adapter
4---
5
6## Installation
7
8```sh
9npm install @tanstack/svelte-db
10```
11
12## Svelte Utilities
13
14See the [Svelte Functions Reference](./reference/index.md) to see the full list of utilities available in the Svelte Adapter.
15
16For comprehensive documentation on writing queries (filtering, joins, aggregations, etc.), see the [Live Queries Guide](../../guides/live-queries).
17
18## Basic Usage
19
20### DbProvider
21
22Use one `DbClient` for each browser app and one per server request. `DbProvider`
23lets queries resolve collection descriptors against that client:
24
25```svelte
26<script lang="ts">
27 import { DbClient, DbProvider } from '@tanstack/svelte-db'
28 import App from './App.svelte'
29
30 const client = new DbClient()
31</script>
32
33<DbProvider {client}>
34 <App />
35</DbProvider>
36```
37
38See [SSR and Hydration](../../guides/ssr.md) for server preloading,
39dehydration, and snapshot handoff.
40
41### useLiveQuery
42
43The `useLiveQuery` utility creates a live query that automatically updates your component when data changes. It returns reactive values powered by Svelte 5 runes:
44
45```svelte
46<script>
47 import { useLiveQuery } from '@tanstack/svelte-db'
48 import { eq } from '@tanstack/db'
49
50 const query = useLiveQuery({
51 query: (q) =>
52 q.from({ todos: todosCollection })
53 .where(({ todos }) => eq(todos.completed, false))
54 .select(({ todos }) => ({ id: todos.id, text: todos.text }))
55 })
56</script>
57
58{#if query.isLoading}
59 <div>Loading...</div>
60{:else}
61 <ul>
62 {#each query.data as todo (todo.id)}
63 <li>{todo.text}</li>
64 {/each}
65 </ul>
66{/if}
67```
68
69**Note:** With Svelte 5, `useLiveQuery` returns reactive values through getters. Access `query.data` and `query.isLoading` directly (no `$` prefix needed).
70
71### useLiveInfiniteQuery
72
73For ordered, paginated data with live updates, use `useLiveInfiniteQuery`:
74
75```svelte
76<script>
77 import { useLiveInfiniteQuery } from '@tanstack/svelte-db'
78 import { eq } from '@tanstack/db'
79
80 let category = $state('news')
81 const query = useLiveInfiniteQuery(
82 (q) =>
83 q
84 .from({ posts: postsCollection })
85 .where(({ posts }) => eq(posts.category, category))
86 .orderBy(({ posts }) => posts.createdAt, 'desc'),
87 { pageSize: 20 },
88 [() => category],
89 )
90</script>
91
92{#each query.data as post (post.id)}
93 <article>{post.title}</article>
94{/each}
95
96{#if query.hasNextPage}
97 <button
98 disabled={query.isFetchingNextPage}
99 onclick={() => query.fetchNextPage()}
100 >
101 Load more
102 </button>
103{/if}
104```
105
106`fetchNextPage()` returns a promise that resolves after the page request settles. A failed page load does not reject the promise or change `status`; it appears as a request error in `query.health`.
107
108The query must include `orderBy`. The dependency array is available only with
109the query-function form. You can also pass an ordered, pre-created live query
110collection directly.
111
112### Query Identity
113
114`useLiveQuery` derives identity from structured query IR. Svelte also tracks
115reactive values read while building the query, so normal builder queries do not
116need a dependency array or `queryKey`.
117
118Captured props and state become part of the derived identity:
119
120```svelte
121<script>
122 import { useLiveQuery } from '@tanstack/svelte-db'
123 import { gt } from '@tanstack/db'
124
125 let { minPriority } = $props()
126
127 const query = useLiveQuery({
128 query: (q) =>
129 q.from({ todos: todosCollection })
130 .where(({ todos }) => gt(todos.priority, minPriority))
131 })
132</script>
133
134<div>{query.data.length} high-priority todos</div>
135```
136
137When the derived identity changes:
1381. The previous live query collection is cleaned up
1392. A new query is created with the updated values
1403. The component re-renders with the new data
1414. The utility shows loading state again
142
143Without a `DbClient`, Svelte compiles again whenever a reactive read changes,
144so an opaque functional variant such as `.fn.where` works without a key. A
145`DbClient` matches preloaded and hydrated queries by identity hash, so a query
146it backs needs one: an opaque query without `queryKey` throws
147`UnhashableQueryIRError`, and an empty `queryKey` counts as none. Pass reactive
148key values through a getter:
149
150```svelte
151<script>
152 import { useLiveQuery } from '@tanstack/svelte-db'
153
154 let search = $state('ship')
155
156 const query = useLiveQuery({
157 queryKey: () => [todosCollection.id, 'search', search],
158 query: (q) =>
159 q.from({ todos: todosCollection })
160 .fn.where(({ todos }) => todos.title.includes(search))
161 })
162</script>
163```
164
165While a `DbClient`-backed query is mounted, each source Collection ID it
166reads must keep naming one Collection object, because its identity names
167sources by ID. A different object under an ID the hook already read throws
168`SourceCollectionIdReuseError`, and every result property then throws instead
169of returning the previous query's state.
170
171The legacy dependency array remains supported. Prefer derived identity for
172structured queries and `queryKey` for opaque ones.
173
174### Accessing Multiple Properties
175
176You can access all status properties directly on the query result:
177
178```svelte
179<script>
180 import { useLiveQuery } from '@tanstack/svelte-db'
181 import { eq } from '@tanstack/db'
182
183 const query = useLiveQuery((q) =>
184 q.from({ todos: todosCollection })
185 .where(({ todos }) => eq(todos.active, true))
186 )
187</script>
188
189<div>
190 <div>Status: {query.status}</div>
191 <div>Loading: {query.isLoading}</div>
192 <div>Ready: {query.isReady}</div>
193 <div>Total: {query.data.length}</div>
194</div>
195```