Start learning free

LESSON 51 OF 161 · FRONTEND: TALKING TO AN API

When the Network Fails

Practice

Sometimes no answer comes at all: the visitor's Wi-Fi drops, or their train goes into a tunnel. Then fetch throws an error. In an async function, an error at an await stops the function right there, so the lines after it never run, and "Loading products…" stays on the screen forever.

try / catch handles it. You put the lines that can fail inside try. If one of them throws, JavaScript skips the rest of try and runs catch instead. The same idea for a list of categories:

try {
  const response = await fetch("/api/categories");
  // ...use the answer
} catch (error) {
  note.textContent = "Categories are not available";
}

A message alone leaves the visitor stuck, so the page also gets a way to ask again: index.html now has a hidden <button id="retry">Try again</button> under the message. The empty try and catch blocks are already in loadProducts. The check goes offline, opens the page, clicks Try again, goes online and clicks again. Your page must show:

> the network goes offline
> open the page
  request: GET /api/products -> failed: the network is offline
  screen:
    …
    text: Can't reach the shop
    button: Try again
    text: 0 products
> click "Try again"
  request: GET /api/products -> failed: the network is offline
  screen: no change
> the network goes online
> click "Try again"
  request: GET /api/products ...
  screen while waiting:
    …
    text: Loading products…
    text: 0 products
  answer: GET /api/products -> 200
  screen changes:
    -  text: Loading products…
    +  text: 8 products
    …

Your task: select #retry, move the request into try, make catch say "Can't reach the shop" and show the button, make a click on it call loadProducts, and hide the button at the start of every try.


Assignment
Follow the Coding Tutorial to catch a failed request, tell the visitor the shop can't be reached, and give them a Try again button that asks once more.


Hint
Give addEventListener the function itself, loadProducts, without parentheses: the click calls it later. With parentheses, it would run once, right away.


STEP 1 OF 9
    Ctrl + Enter to check