Start learning free

LESSON 90 OF 161 · FRONTEND: REACT EFFECTS AND DATA

Show It First, Fix It If Needed in JavaScript

Practice

Most requests succeed. So instead of making the visitor wait, the page can change the screen first and send the request after. This is an optimistic update. If the server says no, the page puts the old state back and tells the visitor.

The trick is to keep a copy of the state before you change it. A star button, for example:

async function toggleStar() {
  const before = starred;
  setStarred(!starred);
  const response = await fetch("/api/star", { method: "PUT" });
  if (!response.ok) {
    setStarred(before);
  }
}

A DELETE has no body: the URL names the thing to remove, like /api/cart/4 for the Pen. And fetch doesn't throw when the server answers 500: a 500 is still an answer, so check response.ok.

Your page must do this (the check makes the Mug's DELETE fail):

> the API will answer DELETE /api/cart/1 with 500
> click "Remove Mug"
  DELETE /api/cart/1 ...   while waiting: Cart (1), only Pen × 1 $2, Total: $2
  answer  →  500           Mug × 1 $12 is back, Total: $14, alert: Could not remove Mug
> click "Remove Pen"
  DELETE /api/cart/4  →  200   Cart (1), Total: $12, the alert is gone

Your task: in src/App.jsx, write removeFromCart: take the line off the cart at once, send the DELETE, and when the answer is not ok, put the old cart back and show "Could not remove Mug" in an alert below the cart.


Assignment
Follow the Coding Tutorial to add a notice state with its alert, and to make removeFromCart remove the line first and undo it when the server says no.


Hint
Keep the cart in before before you call setCart. filter keeps the lines whose product_id is different from the removed one.


STEP 1 OF 9
    Ctrl + Enter to check

    Effect Optimistic in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free