Deviopath › React

Optimistic Updates with Rollback

Hard · Async

Make the checkboxes feel instant with optimistic updates. fakeSave(todo) resolves after 200ms, but saving "Pay rent" always fails.

Each todo is <li data-id="1"> with <label><input type="checkbox" /> Buy milk</label>, and <p className="summary">1 of 3 done</p> is below the list.

- A click flips the todo right away (the summary too) and calls fakeSave with the updated todo.

- While its save is running, the <li> has the class saving and its checkbox is disabled.

- If the save fails, flip only that todo back and show <p className="error">Could not save "Pay rent"</p>. The next successful save hides the message.

- Saves run in parallel: a failure must never undo changes to other todos.

Tip: the Promise finishes after other clicks, so use functional updates (setTodos((list) => ...)).

Next: Multi-Step Form Wizard