This component lets users like or unlike something. It updates the button immediately when clicked. If the server update fails, it changes back and shows an error message.
A. Remove the optimistic update and update only after fetch
B. Add code to revert items state to previous value in catch
C. Ignore errors since optimistic update is enough
D. Add a console.log in catch without state change
Solution
Step 1: Identify missing error handling
Optimistic update changes state immediately, but no revert on failure.
Step 2: Add revert logic in catch block
To keep UI consistent, revert items to previous state if fetch fails.
Final Answer:
Add code to revert items state to previous value in catch -> Option B
Quick Check:
Revert state on error = correct error handling [OK]
Hint: Revert state in catch to fix errors [OK]
Common Mistakes:
Not reverting state on failure
Removing optimistic update unnecessarily
Only logging errors without UI fix
5. You want to implement optimistic updates for a list of tasks in Next.js. The user can add a task, and the UI should update immediately. However, if the server rejects the addition, the UI must revert. Which approach correctly handles this scenario?
hard
A. Update the tasks state immediately, then on server failure, reset tasks to previous state saved before update
B. Wait for server confirmation before updating tasks state to avoid inconsistencies
C. Update tasks state immediately and do nothing on failure, assuming server will eventually succeed
D. Clear the tasks list on server failure to force user refresh
Solution
Step 1: Understand optimistic update with revert
Optimistic update means immediate UI change, but must revert on failure to keep UI correct.
Step 2: Evaluate options for correct revert handling
Update the tasks state immediately, then on server failure, reset tasks to previous state saved before update saves previous state and reverts on failure, matching best practice.
Final Answer:
Update the tasks state immediately, then on server failure, reset tasks to previous state saved before update -> Option A
Quick Check:
Optimistic update + revert = Update the tasks state immediately, then on server failure, reset tasks to previous state saved before update [OK]
Hint: Save old state to revert if server fails [OK]
Common Mistakes:
Not reverting UI on failure
Waiting for server before UI update
Clearing list unnecessarily on error
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.