Start learning free

LESSON 83 OF 161 · FRONTEND: REACT EFFECTS AND DATA

When Loading Fails in JavaScript

Practice

An API can fail. When it answers with an error status, like 500, fetch does not throw: you get an answer with a body, like any other. Its response.ok is true only for a status from 200 to 299, so your code checks it and throws an error itself.

try, catch and finally handle a throw. When a line inside try throws, the rest of the try is skipped and catch runs. finally runs afterwards either way:

try {
  const saved = JSON.parse(text);
  setSettings(saved);
} catch {
  setNotice("Saved settings are broken");
} finally {
  setReady(true);
}

An error state lets the page tell the visitor what went wrong, and a button can call the loading function again. A new try starts fresh: loading again, with no old error.

The check makes the API fail once, then clicks Try again. Your page must print:

> the API will answer GET /api/products with 500
> open the page
  request: GET /api/products -> 500
  alert: Can't load the products
  button: Try again
> click "Try again"
  request: GET /api/products ...
  screen while waiting:
    text: Loading products…
  answer: GET /api/products -> 200
  -   text: Loading products…
  +   section "Products"
  +     text: 8 products

Your task: in src/App.jsx, make loadProducts throw when the answer is not ok, wrap it in try / catch / finally so loading always stops and the error lands in the error state, and show an alert with a Try again button when there is an error.


Assignment
Follow the Coding Tutorial to handle a failed load: check response.ok, catch the error, show Can't load the products and let the visitor try again.


Hint
Code that must run whether the load worked or not goes in finally. If Try again gets the products but the alert stays, look at what error holds when the new try starts.


STEP 1 OF 9
    Ctrl + Enter to check

    Effect Errors 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