Hey everyone, I’m wiring up a cart UI and trying to keep it snappy with optimistic updates, but when two quantity changes happen fast the rollback sometimes hits the newer value instead of the failed one.
@Ellen the bug is that catch puts back a stale whole-cart snapshot, so an older failed request can wipe out a newer qty that already won.
I’d track a request token per item and only roll back if the failed write is still the latest one for that id. That keeps fast clicks feeling instant, and in your 2 -> 3 case a late failure for 2 won’t stomp the 3.
That latestToken.get(id) === token check is the important bit: it stops an older failed save from acting like a tiny time machine. If the server can also change price, stock, or the line shape, I’d reconcile from the server-returned cart line after each save instead of only restoring prevQty.