Skip to content

Commit afc182e

Browse files
committed
Add changeset for writeInsert optimistic state fix
1 parent 051398c commit afc182e

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
---
2+
"@tanstack/db": patch
3+
---
4+
5+
Fix optimistic state not being replaced by server data when using writeInsert in mutation handlers
6+
7+
Previously, when using `writeInsert()` inside an `onInsert` handler to sync server-generated data back to the collection, the optimistic client-side data would not be replaced by the actual server data. This meant that temporary client-side values (like negative IDs) would persist even after the server returned the real values.
8+
9+
**Example of the issue:**
10+
11+
```ts
12+
const todosCollection = createCollection(
13+
queryCollectionOptions({
14+
// ...
15+
onInsert: async ({ transaction }) => {
16+
const newItems = transaction.mutations.map((m) => m.modified)
17+
const serverItems = await createTodos(newItems)
18+
19+
todosCollection.utils.writeBatch(() => {
20+
serverItems.forEach((serverItem) => {
21+
todosCollection.utils.writeInsert(serverItem)
22+
})
23+
})
24+
25+
return { refetch: false }
26+
},
27+
})
28+
)
29+
30+
// User inserts with temporary ID
31+
todosCollection.insert({
32+
id: -1234, // Temporary negative ID
33+
title: "Task"
34+
})
35+
36+
// Server returns real ID, but UI would still show -1234 instead of the real ID
37+
```
38+
39+
This has been fixed by preventing optimistic state from `persisting` transactions from being re-applied during server data synchronization. The UI now correctly updates to show server-generated values once they are synced via `writeInsert()`.

0 commit comments

Comments
 (0)