Skip to content
Source
Sign inSign up
TanStack/db

Fixed query collection bug where optimistic state leaked into syncedData when using writeInsert inside onInsert handlers #879

Mergedsamwillis(GitHub profile, opens in a new tab)merged 1 commit intomain fromrefs/pull/879/headmerged by samwillis(GitHub profile, opens in a new tab)

Showing 3 changed files with 95 additions and 1 deletion.

x
0 of 3 viewed, 3 left
5 additions and 0 deletions.changeset/fix-optimistic-state-in-synced-data.mdAdded
View file
@@ -0,0 +1,5 @@
+---
+"@tanstack/query-db-collection": patch
+---
+​
+Fixed bug where optimistic state leaked into syncedData when using writeInsert inside onInsert handlers. Previously, when syncing server-generated fields (like IDs or timestamps) using writeInsert within an onInsert handler, the QueryClient cache was updated with combined visible state (including optimistic changes), which triggered the query observer to write optimistic values back to syncedData. Now the cache is correctly updated with only server-confirmed state, ensuring syncedData maintains separation from optimistic state.
1 addition and 1 deletionpackages/query-db-collection/src/manual-sync.tsModified
View file
@@ -204,7 +204,7 @@
ctx.commit()
​
// Update query cache after successful commit
- const updatedData = ctx.collection.toArray
+ const updatedData = Array.from(ctx.collection._state.syncedData.values())
ctx.queryClient.setQueryData(ctx.queryKey, updatedData)
​
89 additions and 0 deletionspackages/query-db-collection/tests/query.test.tsModified
View file
@@ -2013,6 +2013,95 @@
expect(collection2.has(`a`)).toBe(true)