Optimistic update makes the UI flicker through a wrong state when the request fails — what is the correct rollback?
Added optimistic updates to a toggle. Happy path is lovely. The failure path is worse than what I had before.
What happens when the request fails: the toggle flips back, then briefly flips again, then settles. Sometimes it settles on the wrong value and stays there until I navigate away and come back.
I am writing to the cache in the mutation and rolling back in the error handler by writing the old value back. That seems to be roughly what the docs show and it clearly is not enough.
I suspect the problem is that a refetch is landing somewhere in the middle, but I cannot work out the ordering. What is the pattern that actually gets this right?
@rollback_reference · 5h ago
Your suspicion is right, and there are two separate bugs producing the two symptoms.
The flicker is an in-flight refetch landing on top of your optimistic write. You write the optimistic value; a query that was already running finishes and writes the server's old value; your error handler then writes your snapshot. Three writes, and the middle one is not yours.
The fix is to cancel outgoing queries for that key before you write optimistically. Every good implementation of this starts with that step and it is the one people skip because the happy path works without it.
The wrong final value is your rollback writing a stale snapshot. If you captured the old value when the mutation was defined rather than immediately before the write, or if two mutations overlap, the value you restore is not the value that was there.
So the correct sequence, in order, and the order is the whole answer:
Step 5 is what fixes the state that persists until you navigate away. Without it, a failed rollback is never corrected by anything.
Reply
Report