Start learning free

LESSON 94 OF 161 · FRONTEND: REACT EFFECTS AND DATA

Project: The Product Panel

Practice

Each product card has a Details button. Clicking it stores the product's id in App, and App draws a ProductPanel with that productId. The panel's look is already written: an alert when error is set, the name, price and stock when product is set, and Loading… when both are null. What's missing is the effect that loads the product.

This project puts the whole module together: an effect with a dependency, an async function inside it, response.ok for an answer that failed, and a cleanup that makes an old answer harmless. Here is the same idea for an order, in another component:

useEffect(() => {
  let ignore = false;
  async function loadOrder() {
    const response = await fetch("/api/orders/" + orderId);
    const data = await response.json();
    if (!ignore) setOrder(data);
  }
  loadOrder();
  return () => {
    ignore = true;
  };
}, [orderId]);

Two more details. A 404 answer has a JSON body too, {"error": "Product not found"}, so read the JSON first, then choose: the product for an ok answer, the error message otherwise. And each time another product is chosen, set product and error back to null first, so the panel shows Loading… instead of the last product or an old error.

The check makes the API answer 404 for the Gift card. Under Check, the page must show:

click "Details" in "Mug"        GET /api/products/1  →  200
  while waiting: Loading…       then: Mug  $12  10 in stock
click "Details" in "Lamp"       GET /api/products/3  →  200
  while waiting: Loading…       then: Lamp  $29  1 in stock
click "Details" in "Gift card"  GET /api/products/8  →  404
                                alert: Product not found
click "Details" in "Pen"        GET /api/products/4  →  200
                                Pen  $2  120 in stock
click "Close"                   the panel is gone

Your task: in src/ProductPanel.jsx, write the effect that loads /api/products/ plus productId each time productId changes, sets product or error from the answer, drops the answer of a run that was cleaned up, and starts every run from Loading….


Assignment
Follow the Coding Tutorial to write the panel's effect in src/ProductPanel.jsx: the effect and its function, the fetch and the JSON, the two outcomes, the ignore flag with its cleanup, and the reset to null.


Hint
The effect itself can't be async, so it holds an async function and calls it. The panel checks error before product, so an error that is never set back to null hides every product after it.


STEP 1 OF 12
    Ctrl + Enter to check