67Implement optimistic UI updates with rollback on failure
mediumAbout 40 minutesCodingreactoptimistic-uistateerror-handling
Problem
Build <TodoList initialTodos={todos} api={api} />. Todos look like { id, text, done }. The API is slow, so the UI must update optimistically, before the server answers, and roll back if the server says no.
api.toggle(id, done)resolves when saved, or rejects.api.add(text)resolves with the saved todo{ id, text, done: false }(with the server's realid), or rejects.
Markup:
- each todo is
<li data-id={id}><label><input type="checkbox" checked={done} /> {text}</label></li>; - a
<form>with<input aria-label="New todo">and a submit button; <p role="alert">with a short message after a failure.
Requirements
- Toggling flips the checkbox immediately; a failure flips it back and shows the alert.
- Adding shows the new todo immediately (with a temporary id and
aria-busy="true"); on success it gets the server's id; on failure it is removed and the alert is shown. - Rolling back one failed change must not undo other changes made in the meantime, for example another todo toggled while the first request was still pending.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
App.jsxReact + DOM
Step-by-step
For a toggle, update state right away with setTodos((list) => …), then call api.toggle. The user sees the change instantly.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.