Skip to main content
Version: v9.0.0(Outdated)

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.

Purpose
  1. Concurrent mutations: why per-item rollbacks keep in-flight mutations independent.
  2. Toggles and batches: the same rule applied to on/off switches and bulk actions.
  3. 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 from previous, 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));
}),
]);
Two mutations on the same field

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​

ScenarioRollback
One item in a listRestore the item from previous, by id
ToggleWrite the opposite value
CreateFilter the temporary id out, swap it in .commit()
DeleteRe-add the item from previous
CounterOpposite increment
BatchRestore the matched items from previous
Hard to undoNo .rollback() - the refresh restores the data

Summary
  • Scope every rollback to its own change: build the result from data, look old values up in previous.
  • 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.