Why is my optimistic cart update rolling back the wrong item?

Ellen1979
Tue, 07 Apr 2026 01:00:10 +0000

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.

let cart = [{ id: 1, qty: 1 }];

async function updateQty(id: number, qty: number) {
  const prev = [...cart];
  cart = cart.map(item => item.id === id ? { ...item, qty } : item);

  try {
    await fakeApiSave(id, qty);
  } catch {
    cart = prev;
  }
}

What is the cleanest way to handle overlapping optimistic writes here without making the UI feel sluggish?

Ellen