tanstack/db/mutations-optimistic
Claude Code and agent skill by tanstack/db
- community
Checking that the SKILL.md file is still in the repository.
collection.insert, collection.update (Immer-style draft proxy), collection.delete. createOptimisticAction (onMutate + mutationFn). createPacedMutations with debounceStrategy, throttleStrategy, queueStrategy. createTransaction, getActiveTransaction, ambient transaction context. Transaction lifecycle (pending/persisting/completed/failed). Mutation merging. onInsert/onUpdate/onDelete handlers. PendingMutation type. Transaction.when('settled').
Install
npx vskill@latest install tanstack/db/mutations-optimisticSKILL.md
The same SKILL.md was published earlier as tanstack/db/mutations-optimistic.
Mutations & Optimistic State
Depends on:db-core/collection-setup-- you need a configured collection(withgetKey, sync adapter, and optionallyonInsert/onUpdate/onDeletehandlers) before you can mutate.
TanStack DB mutations follow a unidirectional loop: optimistic mutation -> handler persists -> handler waits for sync/ack -> confirmed state. Optimistic state is applied in the current tick and dropped when the handler resolves.
Setup -- Collection Write Operations
insert
update (Immer-style draft proxy)
delete
All three return a Transaction object. Use tx.when('settled') to await settlement or catch rollback errors. For a non-empty transaction, this normally means its mutationFn returned; it proves upload, confirmation, or read-back only when that function waits for the backend observation before returning.
Do not start or await collection preloads, live-query preloads, or direct loadSubset() calls inside mutationFn. Sync commits queue behind mutation persistence, so the preload can wait on the mutation that is waiting on it. Use the collection adapter's documented mutation acknowledgement pattern.
Core Patterns
1. createOptimisticAction -- intent-based mutations
Use when the optimistic change is a _guess_ at how the server will transform the data, or when you need to mutate multiple collections atomically.
Multi-collection example:
2. createPacedMutations -- auto-save with debounce / throttle / queue
Other strategies:
3. createTransaction -- manual batching
Inside tx.mutate(() => { ... }), the transaction is pushed onto an ambient stack. Any collection.insert/update/delete call joins the ambient transaction automatically via getActiveTransaction(). That scope is synchronous: collection operations after an await do not join it. Put async work in mutationFn, or call mutate() again before committing.
For mutations captured by a manual transaction, collection-level onInsert/onUpdate/onDelete handlers are not invoked automatically. The manual transaction's mutationFn is responsible for persisting transaction.mutations. This makes createTransaction({ autoCommit: false }) a good fit for draft-style flows where local state updates immediately but the server call waits for Save/Blur; call tx.rollback() to discard the optimistic changes.
4. Mutation handlers with explicit refetch (QueryCollection pattern)
For ElectricCollection, wait for each txid in the Electric stream:
Common Mistakes
CRITICAL: Passing an object to update() instead of a draft callback
CRITICAL: Hallucinating mutation API signatures
The most common AI-generated errors:
- Inventing handler signatures (e.g.
onMutateon a collection config) - Confusing
createOptimisticActionwithcreateTransaction - Wrong PendingMutation property names (
mutation.datadoes not exist --
use mutation.modified, mutation.changes, mutation.original)
- Missing the ambient transaction pattern
Always reference the exact types in references/transaction-api.md.
CRITICAL: onMutate returning a Promise
onMutate in createOptimisticAction must be synchronous. Optimistic state is applied in the current tick. Returning a Promise throws OnMutateMustBeSynchronousError.
CRITICAL: Mutations without handler or ambient transaction
Collection mutations require either:
- An
onInsert/onUpdate/onDeletehandler on the collection, OR - An ambient transaction from
createTransaction/createOptimisticAction
Without either, throws MissingInsertHandlerError (or the Update/Delete variant).
HIGH: Calling .mutate() after transaction is no longer pending
Transactions only accept new mutations while in pending state. Calling mutate() after commit() or rollback() throws TransactionNotPendingMutateError. Create a new transaction instead.
HIGH: Changing primary key via update
The update proxy detects key changes and throws KeyUpdateNotAllowedError. Primary keys are immutable once set. If you need a different key, delete and re-insert.
HIGH: Inserting item with duplicate key
If an item with the same key already exists (synced or optimistic), throws DuplicateKeyError. Always generate a unique key (e.g. safeRandomUUID()) or check before inserting.
HIGH: Returning before Query Collection has confirmed data
Query Collection does not refetch after onInsert, onUpdate, or onDelete. A server write alone leaves synced rows unchanged. When the handler returns, its optimistic state drops, so the previous synced rows reappear.
Alternatively, await a direct-write utility with the confirmed server result. Handlers return Promise<void>; { refetch: false } is no longer supported.
Tension: Optimistic Speed vs. Data Consistency
Instant optimistic updates create a window where client state diverges from server state. If the handler fails, the rollback removes the optimistic state -- which can discard user work the user thought was saved. Consider:
- Showing pending/saving indicators so users know state is unconfirmed
- Using
{ optimistic: false }for destructive operations - Designing idempotent server endpoints so retries are safe
- Handling
tx.when('settled')rejection to surface errors to the user
References
- Transaction API Reference -- createTransaction config,
Transaction object, PendingMutation type, mutation merging rules, strategy types
Security
- Security scanPassed, 100 of 100Pattern checks on the skill's files.
- Model reviewNot runA model review is scheduled for the next rescan.
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingpackages/db/skills/db-core/mutations-optimistic/SKILL.md
Popularity
- Repository stars
- 3,880
- Repository forks
- 258
- 7-day trend score
- 41
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/tanstack/db/mutations-optimistic)