Start learning free

LESSON 130 OF 161 · FRONTEND: FRONTEND WITH AI

The AI Assumed It Works in JavaScript

Practice

An AI assistant wrote the code that loads the Corner Shop's products. It works while the API is fine. But when the API answers 500, the page goes blank. Here is the AI's version:

async function loadProducts() {
  const response = await fetch("/api/products");
  const data = await response.json();
  setProducts(data);
}

fetch doesn't throw on a 500: the answer arrives, with response.ok set to false. Its body is an error object, {"error": "Server error"}, and ProductList calls products.map on it. The result is TypeError: products.map is not a function, and React drops the whole page.

Check ok before you read the body, and keep the problem in state so the page can show it. For a cart, it could look like this:

const response = await fetch("/api/cart");
if (!response.ok) {
  setMessage("The cart is not available.");
  return;
}

The check makes the API answer 500, opens the page, then clicks Try again (the API answers 200 this time):

> open the page       →  request: GET /api/products -> 500
                         alert: Could not load the products (error 500).
                         button: Try again
                         text: 0 products
> click "Try again"   →  request: GET /api/products -> 200
                         the alert and the button go away
                         text: 8 products, Mug $12 to Gift card $50

Your task: in src/App.jsx, add an error state, check response.ok and stop on a failure, show the error in an alert with a Try again button, and clear the error at the start of each try.


Assignment
Follow the Coding Tutorial to give the AI's product list an error state: a check of response.ok that stops before setProducts, an alert, and a Try again button.


Hint
An empty string means no error, so error && … draws nothing until there is one. response.status holds the code for the message.


STEP 1 OF 7
    Ctrl + Enter to check

    Aiui No Error State 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