Skip to content

Commit 27a2e29

Browse files
authored
docs: simplify README usage example. (#70)
1 parent 382783e commit 27a2e29

1 file changed

Lines changed: 41 additions & 83 deletions

File tree

README.md

Lines changed: 41 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@ TanStack DB extends TanStack Query with collections, live queries and transactio
99
<p>
1010
<a href="https://x.com/intent/post?text=TanStack%20DB&url=https://tanstack.com/db">
1111
<img alt="#TanStack" src="https://img.shields.io/twitter/url?color=%2308a0e9&label=%23TanStack&style=social&url=https%3A%2F%2Ftwitter.com%2Fintent%2Ftweet%3Fbutton_hashtag%3DTanStack" /></a>
12-
<a href="https://discord.gg/yjUNbvbraC">
13-
<img alt="" src="https://img.shields.io/badge/Discord-TanStack-%235865F2" /></a>
14-
<a href="https://npmjs.com/package/@tanstack/db">
15-
<img alt="" src="https://img.shields.io/npm/dm/@tanstack/db.svg" /></a>
1612
<a href="#status">
1713
<img src="https://img.shields.io/badge/status-alpha-orange" alt="Status - Alpha"></a>
14+
<a href="https://npmjs.com/package/@tanstack/db">
15+
<img alt="" src="https://img.shields.io/npm/dm/@tanstack/db.svg" /></a>
16+
<a href="https://discord.gg/yjUNbvbraC">
17+
<img alt="" src="https://img.shields.io/badge/Discord-TanStack-%235865F2" /></a>
1818
<a href="https://github.com/tanstack/db/discussions">
1919
<img alt="Join the discussion on Github" src="https://img.shields.io/badge/Discussions-Chat%20now!-green" /></a>
2020
<a href="https://x.com/tan_stack">
@@ -40,28 +40,21 @@ Built on a TypeScript implementation of differential dataflow ([#](https://githu
4040

4141
TanStack DB is **backend agnostic** and **incrementally adoptable**:
4242

43-
- plug in any backend: sync engines, polling APIs, GraphQL, custom sources
43+
- plug in any backend: sync engines, REST APIs, GraphQL, polling, custom sources
4444
- builds on [TanStack Store](https://tanstack.com/store), works with and alongside [TanStack Query](https://tanstack.com/query)
4545

4646
## 💥 Usage example
4747

4848
Sync data into collections:
4949

5050
```ts
51-
import { createElectricCollection } from "@tanstack/db-collections"
52-
53-
// You can configure any strategy you like to load data into
54-
// collections. Here we're using the Electric sync engine.
55-
export const todoCollection = createElectricCollection<Todo>({
56-
id: "todos",
57-
streamOptions: {
58-
url: "https://example.com/v1/shape",
59-
params: {
60-
table: "todos",
61-
},
62-
},
63-
primaryKey: ["id"],
64-
schema: todoSchema, // standard schema interface
51+
import { createQueryCollection } from "@tanstack/db-collections"
52+
53+
const todoCollection = createQueryCollection<TodoList>({
54+
queryKey: ["todos"],
55+
queryFn: async () => fetch("/api/todos"),
56+
getPrimaryKey: (item) => item.id,
57+
schema: todoSchema, // any standard schema
6558
})
6659
```
6760

@@ -72,83 +65,54 @@ import { useLiveQuery } from "@tanstack/react-optimistic"
7265

7366
const Todos = () => {
7467
const { data: todos } = useLiveQuery((query) =>
75-
// You can query across collections with where clauses,
76-
// joins, aggregates, etc. Here we're doing a simple query
77-
// for all the todos that aren't completed.
78-
query
79-
.from({ todoCollection })
80-
.where("@completed", "=", false)
81-
.select("@id", "@text")
82-
.keyBy("@id")
68+
query.from({ todoCollection }).where("@completed", "=", false)
8369
)
8470

8571
return <List items={todos} />
8672
}
8773
```
8874

89-
Define a `mutationFn` to handle persistence of local writes:
75+
Apply transactional writes with local optimistic state:
9076

9177
```tsx
92-
import type { Collection } from "@tanstack/optimistic"
93-
import type { MutationFn, PendingMutation } from "@tanstack/react-optimistic"
94-
95-
const filterOutCollection = (mutation: PendingMutation) => {
96-
const { collection: _, ...rest } = mutation
78+
import { useOptimisticMutation } from "@tanstack/react-optimistic"
9779

98-
return rest
99-
}
80+
const AddTodo = () => {
81+
const addTodo = useOptimisticMutation({
82+
mutationFn: async ({ transaction }) => {
83+
const { collection, ...newTodo } = transaction.mutations[0]!
10084

101-
// You can handle mutations any way you like. Here, we define a
102-
// generic function that POSTs them to the server.
103-
const mutationFn: MutationFn = async ({ transaction }) => {
104-
const payload = transaction.mutations.map(filterOutCollection)
105-
const response = await fetch("https://api.example.com", {
106-
method: "POST",
107-
headers: {
108-
"Content-Type": "application/json",
85+
await axios.post("/api/todos", newTodo)
86+
await collection.invalidate()
10987
},
110-
body: JSON.stringify(payload),
11188
})
11289

113-
if (!response.ok) {
114-
// Throwing an error will rollback the optimistic state.
115-
throw new Error(`HTTP Error: ${response.status}`)
116-
}
117-
118-
const result = await response.json()
119-
120-
// Wait for the transaction to be synced back from the server
121-
// before discarding the optimistic state.
122-
const collection: Collection = transaction.mutations[0]!.collection
123-
await collection.config.sync.awaitTxid(result.txid)
90+
return (
91+
<Button
92+
onClick={() =>
93+
addTodo.mutate(() =>
94+
todoCollection.insert({
95+
id: uuid(),
96+
text: "🔥 Make app faster",
97+
completed: false,
98+
})
99+
)
100+
}
101+
/>
102+
)
124103
}
125104
```
126105

127-
Use it in your components:
106+
## 📚 Docs
128107

129-
```tsx
130-
import { useOptimisticMutation } from "@tanstack/react-optimistic"
108+
See the [Usage guide](./docs/index.md) for more details, including how to do:
131109

132-
const AddTodo = () => {
133-
const tx = useOptimisticMutation({ mutationFn })
134-
135-
const addTodo = () => {
136-
// Triggers the mutationFn to sync data in the background.
137-
tx.mutate(() =>
138-
// Instantly applies the local optimistic state.
139-
todoCollection.insert({
140-
id: uuid(),
141-
text: "🔥 Make app faster",
142-
completed: false,
143-
})
144-
)
145-
}
146-
147-
return <Button onClick={addTodo} />
148-
}
149-
```
110+
- real-time sync
111+
- cross-collection queries
112+
- fine-grained reactivity
113+
- different strategies for data loading and handling mutations
150114

151-
For transactional writes with local optimistic state and managed background sync.
115+
There's also an example [React todo app](./examples/react/todo) and usage examples in the [package tests](./packages/optimistic/tests).
152116

153117
## 🧱 Core concepts
154118

@@ -173,12 +137,6 @@ For transactional writes with local optimistic state and managed background sync
173137
npm install @tanstack/db
174138
```
175139

176-
## 📚 Docs
177-
178-
See the [Documentation](./docs/index.md) for usage guides and the API reference.
179-
180-
There's also an example [React todo app](./examples/react/todo).
181-
182140
## ❓ FAQ
183141

184142
**How is this different from TanStack Query?**<br />

0 commit comments

Comments
 (0)