Deviopath › Next.js

Optimistic Cart with useOptimistic

Hard · Server Actions

useOptimistic(state, updateFn) shows a temporary value while an async action runs. When the action (the surrounding transition) finishes, React drops the optimistic value and shows the real state again. So a failed request reverts on its own, and a successful one shows the confirmed value you stored in state.

updateQuantity(productId, quantity) in the starter is a fake Server Action (30 ms). It returns { ok: true, quantity } or { ok: false, error }: the Cap is Out of stock, and more than 3 of an item gives Max 3 per item.

- Each product is <li data-id="tee"> with <span className="qty">, <button className="dec">-</button> and <button className="inc">+</button>. Below the list show <p className="total">Items: N</p> (sum of the shown quantities).

- Clicking + or - shows the new quantity immediately, then calls the action with that quantity. Call the optimistic setter inside startTransition(async () => { ... }).

- Optimistic updates should carry an absolute quantity ({ id, quantity }), not "add 1": React re-applies pending optimistic updates whenever the base state changes, so deltas could be counted twice.

- On success store the confirmed quantity in normal state. On failure show <p className="error">Could not update <name>: <error></p> (for example Could not update Cap: Out of stock); the quantity reverts by itself.

- Starting a new update clears the error. - is disabled when the shown quantity is 0.

- Quick clicks each send the next quantity (1, 2, 3, …) based on the quantity currently shown.

Next: Locale Routing with a Default Locale Without Prefix