|
2 | 2 | title: Quick Start
|
3 | 3 | id: quick-start
|
4 | 4 | ---
|
| 5 | + |
| 6 | +TanStack DB is a reactive client store for building super fast apps. This example will show you how to: |
| 7 | + |
| 8 | +- **Load data** into collections using TanStack Query |
| 9 | +- **Query data** with blazing fast live queries |
| 10 | +- **Mutate data** with instant optimistic updates |
| 11 | + |
| 12 | +```tsx |
| 13 | +import { createCollection, useLiveQuery } from '@tanstack/react-db' |
| 14 | +import { queryCollectionOptions } from '@tanstack/query-db-collection' |
| 15 | + |
| 16 | +// Define a collection that loads data using TanStack Query |
| 17 | +const todoCollection = createCollection( |
| 18 | + queryCollectionOptions({ |
| 19 | + queryKey: ['todos'], |
| 20 | + queryFn: async () => { |
| 21 | + const response = await fetch('/api/todos') |
| 22 | + return response.json() |
| 23 | + }, |
| 24 | + getKey: (item) => item.id, |
| 25 | + onUpdate: async ({ transaction }) => { |
| 26 | + const { original, modified } = transaction.mutations[0] |
| 27 | + await fetch(`/api/todos/${original.id}`, { |
| 28 | + method: 'PUT', |
| 29 | + body: JSON.stringify(modified), |
| 30 | + }) |
| 31 | + }, |
| 32 | + }) |
| 33 | +) |
| 34 | + |
| 35 | +function Todos() { |
| 36 | + // Live query that updates automatically when data changes |
| 37 | + const { data: todos } = useLiveQuery((q) => |
| 38 | + q.from({ todo: todoCollection }) |
| 39 | + .where(({ todo }) => !todo.completed) |
| 40 | + .orderBy(({ todo }) => todo.createdAt, 'desc') |
| 41 | + ) |
| 42 | + |
| 43 | + const toggleTodo = (todo) => { |
| 44 | + // Instantly applies optimistic state, then syncs to server |
| 45 | + todoCollection.update(todo.id, (draft) => { |
| 46 | + draft.completed = !draft.completed |
| 47 | + }) |
| 48 | + } |
| 49 | + |
| 50 | + return ( |
| 51 | + <ul> |
| 52 | + {todos.map((todo) => ( |
| 53 | + <li key={todo.id} onClick={() => toggleTodo(todo)}> |
| 54 | + {todo.text} |
| 55 | + </li> |
| 56 | + ))} |
| 57 | + </ul> |
| 58 | + ) |
| 59 | +} |
| 60 | +``` |
| 61 | + |
| 62 | +You now have collections, live queries, and optimistic mutations! Let's break this down further. |
| 63 | + |
| 64 | +## Installation |
| 65 | + |
| 66 | +```bash |
| 67 | +npm install @tanstack/react-db @tanstack/query-db-collection |
| 68 | +``` |
| 69 | + |
| 70 | +## 1. Create a Collection |
| 71 | + |
| 72 | +Collections store your data and handle persistence. The `queryCollectionOptions` loads data using TanStack Query and defines mutation handlers for server sync: |
| 73 | + |
| 74 | +```tsx |
| 75 | +const todoCollection = createCollection( |
| 76 | + queryCollectionOptions({ |
| 77 | + queryKey: ['todos'], |
| 78 | + queryFn: async () => { |
| 79 | + const response = await fetch('/api/todos') |
| 80 | + return response.json() |
| 81 | + }, |
| 82 | + getKey: (item) => item.id, |
| 83 | + // Handle all CRUD operations |
| 84 | + onInsert: async ({ transaction }) => { |
| 85 | + const { modified: newTodo } = transaction.mutations[0] |
| 86 | + await fetch('/api/todos', { |
| 87 | + method: 'POST', |
| 88 | + body: JSON.stringify(newTodo), |
| 89 | + }) |
| 90 | + }, |
| 91 | + onUpdate: async ({ transaction }) => { |
| 92 | + const { original, modified } = transaction.mutations[0] |
| 93 | + await fetch(`/api/todos/${original.id}`, { |
| 94 | + method: 'PUT', |
| 95 | + body: JSON.stringify(modified), |
| 96 | + }) |
| 97 | + }, |
| 98 | + onDelete: async ({ transaction }) => { |
| 99 | + const { original } = transaction.mutations[0] |
| 100 | + await fetch(`/api/todos/${original.id}`, { method: 'DELETE' }) |
| 101 | + }, |
| 102 | + }) |
| 103 | +) |
| 104 | +``` |
| 105 | + |
| 106 | +## 2. Query with Live Queries |
| 107 | + |
| 108 | +Live queries reactively update when data changes. They support filtering, sorting, joins, and transformations: |
| 109 | + |
| 110 | +```tsx |
| 111 | +function TodoList() { |
| 112 | + // Basic filtering and sorting |
| 113 | + const { data: incompleteTodos } = useLiveQuery((q) => |
| 114 | + q.from({ todo: todoCollection }) |
| 115 | + .where(({ todo }) => !todo.completed) |
| 116 | + .orderBy(({ todo }) => todo.createdAt, 'desc') |
| 117 | + ) |
| 118 | + |
| 119 | + // Transform the data |
| 120 | + const { data: todoSummary } = useLiveQuery((q) => |
| 121 | + q.from({ todo: todoCollection }) |
| 122 | + .select(({ todo }) => ({ |
| 123 | + id: todo.id, |
| 124 | + summary: `${todo.text} (${todo.completed ? 'done' : 'pending'})`, |
| 125 | + priority: todo.priority || 'normal' |
| 126 | + })) |
| 127 | + ) |
| 128 | + |
| 129 | + return <div>{/* Render todos */}</div> |
| 130 | +} |
| 131 | +``` |
| 132 | + |
| 133 | +## 3. Optimistic Mutations |
| 134 | + |
| 135 | +Mutations apply instantly and sync to your server. If the server request fails, changes automatically roll back: |
| 136 | + |
| 137 | +```tsx |
| 138 | +function TodoActions({ todo }) { |
| 139 | + const addTodo = () => { |
| 140 | + todoCollection.insert({ |
| 141 | + id: crypto.randomUUID(), |
| 142 | + text: 'New todo', |
| 143 | + completed: false, |
| 144 | + createdAt: new Date(), |
| 145 | + }) |
| 146 | + } |
| 147 | + |
| 148 | + const toggleComplete = () => { |
| 149 | + todoCollection.update(todo.id, (draft) => { |
| 150 | + draft.completed = !draft.completed |
| 151 | + }) |
| 152 | + } |
| 153 | + |
| 154 | + const updateText = (newText) => { |
| 155 | + todoCollection.update(todo.id, (draft) => { |
| 156 | + draft.text = newText |
| 157 | + }) |
| 158 | + } |
| 159 | + |
| 160 | + const deleteTodo = () => { |
| 161 | + todoCollection.delete(todo.id) |
| 162 | + } |
| 163 | + |
| 164 | + return ( |
| 165 | + <div> |
| 166 | + <button onClick={addTodo}>Add Todo</button> |
| 167 | + <button onClick={toggleComplete}>Toggle</button> |
| 168 | + <button onClick={() => updateText('Updated!')}>Edit</button> |
| 169 | + <button onClick={deleteTodo}>Delete</button> |
| 170 | + </div> |
| 171 | + ) |
| 172 | +} |
| 173 | +``` |
| 174 | + |
| 175 | +## Next Steps |
| 176 | + |
| 177 | +You now understand the basics of TanStack DB! The collection loads and persists data, live queries provide reactive views, and mutations give instant feedback with automatic server sync. |
| 178 | + |
| 179 | +Explore the docs to learn more about: |
| 180 | + |
| 181 | +- **[Installation](./installation.md)** - All framework and collection packages |
| 182 | +- **[Overview](./overview.md)** - Complete feature overview and examples |
| 183 | +- **[Live Queries](./live-queries.md)** - Advanced querying, joins, and aggregations |
0 commit comments