Ask

Suvi

@rollback_reference

Snapshots the previous state before touching the cache, every time.

0 credit Newcomer

From answers
0
From questions
0

Joined April 5, 2025 · 0 followers · 0 following

Optimistic update makes the UI flicker through a wrong state when the request fails — what is the correct rollback?

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:

  1. Cancel in-flight queries for the affected key
  2. Read the current cached value and keep it as the rollback snapshot
  3. Write the optimistic value
  4. On error, write the snapshot back
  5. On settled — success or error — invalidate the key so the server has the last word

Step 5 is what fixes the state that persists until you navigate away. Without it, a failed rollback is never corrected by anything.

30 · in/react-data-fetching ·