Advanced Optimistic Patterns
The Optimistic Updates guide covers helpers, .rollback() and when
things settle. This guide collects the patterns for real applications: many mutations on one list, toggles, batches and
several caches at once.
- Concurrent mutations: why per-item rollbacks keep in-flight mutations independent.
- Toggles and batches: the same rule applied to on/off switches and bulk actions.
- Several caches: one mutation keeping a list, a counter and every filter in step.
Concurrent mutations on one list
A user toggles several todos quickly; every mutation changes getTodos. Core keeps them apart:
- Each rollback receives the current
data, so reverting one mutation keeps the others' changes - as long as the rollback only touches its own item. Restore the item fromprevious, never the whole list. - Fetch responses for the list are held back while any of the mutations is pending, so a refetch can't overwrite them.
- The list is refreshed once, after the last mutation settles, and the server's data replaces the optimistic one.
const toggleTodo = client
.createRequest<{ response: Todo; payload: { completed: boolean } }>()({
endpoint: "/todos/:todoId",
method: "PATCH",
})
.setOptimistic(({ params, payload }) => [
optimistic(getTodos)
.patch(params.todoId, payload)
// Restores this item only - other pending toggles are untouched
.rollback(({ data, previous }) => {
const before = previous.find((todo) => todo.id === Number(params.todoId));
return data.map((todo) => (todo.id === Number(params.todoId) && before ? before : todo));
}),
]);
When two pending toggles change the same field and the earlier one fails, its rollback restores the value it saw before its own change. The refresh after the last toggle settles replaces it with the server's value either way.
Toggles
Flip back with the opposite value instead of a snapshot:
const togglePin = client
.createRequest<{ response: Todo; payload: { pinned: boolean } }>()({
endpoint: "/todos/:todoId/pin",
method: "PATCH",
})
.setOptimistic(({ params, payload }) => [
optimistic(getTodos)
.patch(params.todoId, payload)
.rollback(({ data }) =>
data.map((todo) => (todo.id === Number(params.todoId) ? { ...todo, pinned: !payload.pinned } : todo)),
),
]);
Batches
Match many items with a predicate and restore each from previous:
const completeAll = client
.createRequest<{ response: { updated: number }; payload: { todoIds: number[] } }>()({
endpoint: "/todos/complete-all",
method: "POST",
})
.setOptimistic(({ payload }) => {
const ids = new Set(payload.todoIds);
return [
optimistic(getTodos)
.patch((todo) => ids.has(todo.id), { completed: true })
.rollback(({ data, previous }) => {
const before = new Map(previous.filter((todo) => ids.has(todo.id)).map((todo) => [todo.id, todo]));
return data.map((todo) => before.get(todo.id) ?? todo);
}),
];
});
Several caches at once
Return one change per target. They are applied in order and reverted in reverse order, each target is refreshed on its own, and a target without data is skipped.
const completeTodo = client
.createRequest<{ response: Todo }>()({ endpoint: "/todos/:todoId/complete", method: "PATCH" })
.setOptimistic(({ params }) => [
// Every filter and page of the list
optimistic
.all(getTodos)
.patch(params.todoId, { completed: true })
.rollback(({ data }) =>
data.map((todo) => (todo.id === Number(params.todoId) ? { ...todo, completed: false } : todo)),
),
// A counter in another entry
optimistic(getStats)
.increment("completed", 1)
.rollback(({ data }) => ({ ...data, completed: data.completed - 1 })),
]);
Guidelines
| Scenario | Rollback |
|---|---|
| One item in a list | Restore the item from previous, by id |
| Toggle | Write the opposite value |
| Create | Filter the temporary id out, swap it in .commit() |
| Delete | Re-add the item from previous |
| Counter | Opposite increment |
| Batch | Restore the matched items from previous |
| Hard to undo | No .rollback() - the refresh restores the data |
- Scope every rollback to its own change: build the result from
data, look old values up inprevious. - Core holds back stale fetch responses and refreshes each target once, after its last pending mutation.
- Use
optimistic.all()and several operations to keep lists, counters and pages in step.
