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

overview.md

258 lines6.6 KB

1---
2title: TanStack DB Vue Adapter
3id: adapter
4---
5​
6## Installation
7​
8```sh
9npm install @tanstack/vue-db
10```
11​
12## Vue Composables
13​
14See the [Vue Functions Reference](./reference/index.md) to see the full list of composables available in the Vue 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### useLiveQuery
21​
22The `useLiveQuery` composable creates a live query that automatically updates your component when data changes. It returns reactive computed refs:
23​
24```vue
25<script setup>
26import { useLiveQuery } from '@tanstack/vue-db'
27import { eq } from '@tanstack/db'
28​
29const { data, isLoading } = useLiveQuery((q) =>
30 q.from({ todos: todosCollection })
31 .where(({ todos }) => eq(todos.completed, false))
32 .select(({ todos }) => ({ id: todos.id, text: todos.text }))
34</script>
35​
36<template>
37 <div v-if="isLoading">Loading...</div>
38 <ul v-else>
39 <li v-for="todo in data" :key="todo.id">{{ todo.text }}</li>
40 </ul>
41</template>
42```
43​
44**Note:** All return values (`data`, `isLoading`, `status`, etc.) are computed refs, so access them with `.value` in `<script>` but directly in `<template>`.
45​
46### useLiveInfiniteQuery
47​
48For ordered, paginated data with live updates, use `useLiveInfiniteQuery`:
49​
50```vue
51<script setup>
52import { ref } from 'vue'
53import { useLiveInfiniteQuery } from '@tanstack/vue-db'
54import { eq } from '@tanstack/db'
55​
56const category = ref('news')
57const { data, fetchNextPage, hasNextPage, isFetchingNextPage } =
58 useLiveInfiniteQuery(
59 (q) =>
60 q
61 .from({ posts: postsCollection })
62 .where(({ posts }) => eq(posts.category, category.value))
63 .orderBy(({ posts }) => posts.createdAt, 'desc'),
64 { pageSize: 20 },
65 [category],
66 )
67</script>
68​
69<template>
70 <article v-for="post in data" :key="post.id">
71 {{ post.title }}
72 </article>
73 <button
74 v-if="hasNextPage"
75 :disabled="isFetchingNextPage"
76 @click="fetchNextPage()"
77 >
78 Load more
79 </button>
80</template>
81```
82​
83`fetchNextPage()` returns a promise that resolves after the page request settles. Failures are exposed through the returned `error` ref and do not reject the promise.
84​
85The query must include `orderBy`. The dependency array is available only with
86the query-function form. You can also pass an ordered, pre-created live query
87collection directly.
88​
89### Dependency Arrays
90​
91The `useLiveQuery` composable accepts an optional dependency array as its last parameter. When any reactive value in the array changes, the query is recreated and re-executed.
92​
93#### When to Use Dependency Arrays
94​
95Use dependency arrays when your query depends on external reactive values (refs, props, or reactive objects):
96​
97```vue
98<script setup>
99import { ref } from 'vue'
100import { useLiveQuery } from '@tanstack/vue-db'
101import { gt } from '@tanstack/db'
102​
103const minPriority = ref(5)
104​
105const { data } = useLiveQuery(
106 (q) => q.from({ todos: todosCollection })
107 .where(({ todos }) => gt(todos.priority, minPriority.value)),
108 [minPriority] // Pass the ref directly, it will be unwrapped automatically
110</script>
111​
112<template>
113 <div>{{ data.length }} high-priority todos</div>
114</template>
115```
116​
117**Important:** Pass refs directly in the dependency array, not as functions. Vue will automatically track them.
118​
119#### What Happens When Dependencies Change
120​
121When a dependency value changes:
1221. The previous live query collection is cleaned up
1232. A new query is created with the updated values
1243. The component re-renders with the new data
1254. The composable shows loading state again
126​
127#### Best Practices
128​
129**Include all external refs used in the query:**
130​
131```vue
132<script setup>
133import { ref } from 'vue'
134import { useLiveQuery } from '@tanstack/vue-db'
135import { eq, and } from '@tanstack/db'
136​
137const userId = ref(1)
138const status = ref('active')
139​
140// Good - all refs in deps array
141const { data } = useLiveQuery(
142 (q) => q.from({ todos: todosCollection })
143 .where(({ todos }) => and(
144 eq(todos.userId, userId.value),
145 eq(todos.status, status.value)
146 )),
147 [userId, status] // Pass refs directly
149​
150// Bad - missing dependencies
151const { data: badData } = useLiveQuery(
152 (q) => q.from({ todos: todosCollection })
153 .where(({ todos }) => eq(todos.userId, userId.value)),
154 [] // Missing userId!
156</script>
157​
158<template>
159 <div>{{ data.length }} todos</div>
160</template>
161```
162​
163**Using with props:**
164​
165```vue
166<script setup>
167import { toRef } from 'vue'
168import { useLiveQuery } from '@tanstack/vue-db'
169import { eq } from '@tanstack/db'
170​
171const props = defineProps<{ userId: number }>()
172​
173// Option 1: Convert prop to ref
174const userIdRef = toRef(props, 'userId')
175const { data } = useLiveQuery(
176 (q) => q.from({ todos: todosCollection })
177 .where(({ todos }) => eq(todos.userId, userIdRef.value)),
178 [userIdRef]
180​
181// Option 2: Use a getter function for the prop
182const { data: data2 } = useLiveQuery(
183 (q) => q.from({ todos: todosCollection })
184 .where(({ todos }) => eq(todos.userId, props.userId)),
185 [() => props.userId] // Getter function for non-ref values
187</script>
188​
189<template>
190 <div>{{ data.length }} todos</div>
191</template>
192```
193​
194**Empty array for static queries:**
195​
196```vue
197<script setup>
198import { useLiveQuery } from '@tanstack/vue-db'
199​
200// No external dependencies - query never changes
201const { data } = useLiveQuery(
202 (q) => q.from({ todos: todosCollection }),
203 []
205</script>
206​
207<template>
208 <div>{{ data.length }} todos</div>
209</template>
210```
211​
212**Omit the array for queries with no external dependencies:**
213​
214```vue
215<script setup>
216import { useLiveQuery } from '@tanstack/vue-db'
217​
218// Same as above - no deps needed
219const { data } = useLiveQuery(
220 (q) => q.from({ todos: todosCollection })
222</script>
223​
224<template>
225 <div>{{ data.length }} todos</div>
226</template>
227```
228​
229### Using Pre-created Collections
230​
231You can also pass an existing collection to `useLiveQuery`. This is useful for sharing queries across components:
232​
233```vue
234<script setup>
235import { ref } from 'vue'
236import { createLiveQueryCollection } from '@tanstack/db'
237import { useLiveQuery } from '@tanstack/vue-db'
238import { eq } from '@tanstack/db'
239​
240// Create collection outside component or in a composable
241const todosQuery = createLiveQueryCollection({
242 query: (q) => q.from({ todos: todosCollection })
243 .where(({ todos }) => eq(todos.active, true)),
244 startSync: true
245})
246​
247// Use the pre-created collection
248const { data, collection } = useLiveQuery(todosQuery)
249​
250// Or use a reactive ref to switch between collections
251const currentQuery = ref(todosQuery)
252const { data: reactiveData } = useLiveQuery(currentQuery)
253</script>
254​
255<template>
256 <div>{{ data.length }} todos</div>
257</template>
258```