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

overview.md

186 lines4.8 KB

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. Failures are exposed through `query.error` and do not reject the promise.
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​
143Use `queryKey` for opaque functional variants such as `.fn.where`, because DB
144cannot inspect their closed-over values. Pass reactive key values through a
145getter:
146​
147```svelte
148<script>
149 import { useLiveQuery } from '@tanstack/svelte-db'
150​
151 let search = $state('ship')
152​
153 const query = useLiveQuery({
154 queryKey: () => [todosCollection.id, 'search', search],
155 query: (q) =>
156 q.from({ todos: todosCollection })
157 .fn.where(({ todos }) => todos.title.includes(search))
158 })
159</script>
160```
161​
162The legacy dependency array remains supported. Prefer derived identity for
163structured queries and `queryKey` for opaque ones.
164​
165### Accessing Multiple Properties
166​
167You can access all status properties directly on the query result:
168​
169```svelte
170<script>
171 import { useLiveQuery } from '@tanstack/svelte-db'
172 import { eq } from '@tanstack/db'
173​
174 const query = useLiveQuery((q) =>
175 q.from({ todos: todosCollection })
176 .where(({ todos }) => eq(todos.active, true))
177 )
178</script>
179​
180<div>
181 <div>Status: {query.status}</div>
182 <div>Loading: {query.isLoading}</div>
183 <div>Ready: {query.isReady}</div>
184 <div>Total: {query.data.length}</div>
185</div>
186```