The page now has a details panel. When the address is /?product=3, the page asks the API for one product: GET /api/products/3. The end of the file already reads the id from the address into productId and shows the panel. Ask for an id that doesn't exist, like 99, and the API answers 404 with {"error": "Product not found"}.
Here is the surprise: fetch only throws when no answer comes back at all. A 404 is an answer, so await fetch(…) hands you a response as usual. To know how it went, look at response.ok: it is true for statuses 200 to 299, and false for all others, like 404 or 500.
const response = await fetch("/api/products/42");
console.log(response.status, response.ok); // 404 false
Without a check, your code reads the error body as if it were a product. That body has no name, price or stock, so the visitor would read undefined three times. Under Check, your page must show:
> open /?product=3
request: GET /api/products -> 200
request: GET /api/products/3 -> 200
screen:
section "Details"
text: Lamp $29, 1 in stock
> open /?product=99
request: GET /api/products -> 200
request: GET /api/products/99 -> 404
screen:
section "Details"
text: Product not found
Your task: write async function loadDetails(id) that asks for "/api/products/" + id and writes the name, price and stock into details, and call it with productId. Then, when response.ok is false, show "Product not found" and stop.
Assignment
Follow the Coding Tutorial to load one product into the details panel, and to show "Product not found" when the API answers 404.
Hint
Put the check right after the fetch, before response.json(). Inside it, return stops the function; without it, the next lines run anyway and overwrite your message.
Free plan: 30 tutor messages. PRO is unlimited.
