Optimistic rollback
Optimistic rollback restores a snapshot of local state when an optimistic operation fails. To avoid overwriting newer cart edits, restore the snapshot only when the current lines array is still the same reference produced by the optimistic update.
Minimal example
const before = useCart.getState();
const optimisticLines = useCart.getState().lines;
if (useCart.getState().lines === optimisticLines) {
useCart.setState({
restaurantId: before.restaurantId,
lines: before.lines,
idempotencyKey: before.idempotencyKey,
});
}Learn this concept
Lesson 4.19 · Resilient client patternsUsed in exercises
Exercise 4.21 · Cart synchronization helperRelatedIdempotency key