Command Palette

Search for a command to run...

Hectal
Phase 19: React 19: Actions and Modern Forms
React · Exercise 4 of 5 PreviousNext
Advanced

Optimistic likes that revert

The like counter waits 400 ms for the server before the number changes. Make it optimistic with useOptimistic: the number in #count goes up by one immediately when #like or #like-fail is clicked.

fakeLike(ok) resolves when ok is true and rejects otherwise. On success, update the real likes state. On failure, leave likes alone (the optimistic number reverts by itself) and show <p id="error">Could not like</p>.

Remember: addOptimistic must run inside startTransition, and state updates after await go in startTransition too.

What Check tests

  1. The code uses useOptimistic
  2. Clicking #like shows 11 right away, before the server answers
  3. After the server confirms, it still shows 11
  4. Clicking #like-fail shows 12 right away
  5. When the server fails, it goes back to 11 and #error says Could not like

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Your page

Press Run to see the page.

Console

Nothing logged yet.