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

overview.md

168 lines6.2 KB

1---
2title: TanStack DB Preact Adapter
3id: adapter
4---
5​
6## Installation
7​
8```sh
9npm install @tanstack/preact-db
10```
11​
12`@tanstack/preact-db` supports Preact 10 and later and ships as ES modules.
13​
14Queries read concrete source Collections. Preact has no `DbProvider` yet, so it does not bind collection descriptors or read from a `DbClient`; a query over a descriptor throws when it is consumed. Use `@tanstack/react-db` or `@tanstack/svelte-db` for `DbClient`-based SSR and hydration.
15​
16## Preact Hooks
17​
18See the [Preact Functions Reference](./reference/index.md) to see the full list of hooks available in the Preact Adapter.
19​
20For comprehensive documentation on writing queries (filtering, joins, aggregations, etc.), see the [Live Queries Guide](../../guides/live-queries).
21​
22## Basic Usage
23​
24### useLiveQuery
25​
26The `useLiveQuery` hook creates a live query that automatically updates your component when data changes:
27​
28```tsx
29import { createCollection, eq, localOnlyCollectionOptions } from '@tanstack/db'
30import { useLiveQuery } from '@tanstack/preact-db'
31​
32type Todo = {
33 id: string
34 text: string
35 completed: boolean
37​
38const todoCollection = createCollection(
39 localOnlyCollectionOptions<Todo>({
40 getKey: (todo) => todo.id,
41 initialData: [],
42 }),
44​
45function TodoList() {
46 const { data, isLoading } = useLiveQuery((q) =>
47 q
48 .from({ todos: todoCollection })
49 .where(({ todos }) => eq(todos.completed, false))
50 .select(({ todos }) => ({ id: todos.id, text: todos.text })),
51 )
52​
53 if (isLoading) return <div>Loading...</div>
54​
55 return (
56 <ul>
57 {data.map((todo) => (
58 <li key={todo.id}>{todo.text}</li>
59 ))}
60 </ul>
61 )
63```
64​
65`useLiveQuery` accepts a query callback, a `{ query }` config object, or an existing live-query Collection. Return `undefined` or `null` from the callback to disable the query; a disabled query reports `status: 'disabled'` and has no `data` or `state`:
66​
67```tsx
68function UserTodos({ userId }: { userId?: string }) {
69 const { data, isEnabled } = useLiveQuery((q) =>
70 userId
71 ? q
72 .from({ todos: todoCollection })
73 .where(({ todos }) => eq(todos.userId, userId))
74 : undefined,
75 )
76​
77 if (!isEnabled) return <div>Select a user</div>
78 return <div>{data?.length} todos</div>
80```
81​
82### Query Identity
83​
84Preact live query hooks derive the live query identity from structured query IR. The hook runs the query builder on each render, normalizes the resulting IR, and uses that as the identity. When the derived identity changes, the old live query collection is cleaned up and a new one is created.
85​
86That means normal structured queries need no `queryKey` and no dependency array. Captured values inside structured expressions become part of the derived identity:
87​
88```tsx
89function FilteredTodos({ minPriority }: { minPriority: number }) {
90 const { data } = useLiveQuery((q) =>
91 q
92 .from({ todos: todoCollection })
93 .where(({ todos }) => gt(todos.priority, minPriority)),
94 )
95​
96 return <div>{data.length} high-priority todos</div>
98```
99​
100While a hook is mounted, each source Collection ID its queries read must keep referring to the same Collection object. If a render supplies a different source object with a previously used ID, the hook throws `SourceCollectionIdReuseError` instead of returning rows from the old source. To reuse an ID, unmount the hook, clean up its source, then mount the replacement. Separate hooks can use the same ID.
101​
102#### When to Use Query Keys
103​
104Use `queryKey` when DB cannot derive identity from structured IR. The common case is a functional query variant such as `.fn.where`, `.fn.select`, or `.fn.having`. Without a `queryKey`, such a query throws `UnhashableQueryIRError`:
105​
106```tsx
107function SearchTodos({ search }: { search: string }) {
108 const { data } = useLiveQuery({
109 queryKey: [todoCollection.id, 'search', search],
110 query: (q) =>
111 q
112 .from({ todos: todoCollection })
113 .fn.where(({ todos }) =>
114 todos.text.toLowerCase().includes(search.toLowerCase()),
115 ),
116 })
117​
118 return <div>{data.length} matching todos</div>
120```
121​
122An explicit `queryKey` is the caller's identity contract. Represent every value the opaque logic captures in the key, and change the key when its source object changes, even if the source ID stays the same. Use a primitive scope token in the key; Collection objects cannot be hashed there.
123​
124#### What Happens When Identity Changes
125​
126When the derived identity or explicit query key changes:
127​
1281. The previous live query collection is cleaned up
1292. A new query is created with the updated values
1303. The component re-renders with the new data
131​
132### useLiveInfiniteQuery
133​
134For paginated data with live updates, use `useLiveInfiniteQuery`:
135​
136```tsx
137const { data, pages, fetchNextPage, hasNextPage } = useLiveInfiniteQuery(
138 (q) =>
139 q
140 .from({ posts: postsCollection })
141 .where(({ posts }) => eq(posts.category, category))
142 .orderBy(({ posts }) => posts.createdAt, 'desc'),
143 {
144 pageSize: 20,
145 },
147```
148​
149The query must include `.orderBy()`. The hook keeps one live query collection and widens its window as pages load, so every loaded page stays live. Its identity follows `useLiveQuery`: pass `queryKey` in the config for a functional query variant.
150​
151`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 the returned `health` tree.
152​
153This hook widens an ordered live query; it is not TanStack Query's `useInfiniteQuery`. `getNextPageParam` is rejected. `initialPageParam` only labels the returned pages; it does not set a server cursor or skip remote rows. For server pagination, use an on-demand Query Collection whose `queryFn` fulfills `meta.loadSubsetOptions`. See the [server pagination guide](../../collections/query-collection.md#server-pagination-with-live-queries).
154​
155### Using Pre-created Collections
156​
157Pass an existing live query collection to share one query across components. The hook starts its sync and leaves its retention policy to the caller:
158​
159```tsx
160const activeTodos = createLiveQueryCollection((q) =>
161 q.from({ todos: todoCollection }).where(({ todos }) => eq(todos.active, true)),
163​
164function ActiveTodos() {
165 const { data, collection } = useLiveQuery(activeTodos)
166 return <div>{data.length} active todos</div>
168```