JavaScript From Zero · 20 min · 150 XP

Loading, empty and error states

Show loading, empty and error states on the page, and keep the button honest while a request runs.

The last lesson's loadOrders either returns orders or throws. On a page, that turns into four things a person can see, and this lesson is about showing each of them clearly.

Four outcomes on the page

On the page, a request has more than two outcomes. It starts loading, then it succeeds with data, succeeds with nothing (an empty list is an answer, not an error), or fails. Show each one: say Loading… and disable the button that started it, render the data or an honest empty message, and on failure say so in words a person understands. try/catch/finally fits exactly: finally re-enables the button whichever way it went.

A Load button that shows every outcome
const button = document.querySelector("#load-reviews");
const list = document.querySelector("#reviews");
const status = document.querySelector("#review-status");

async function loadReviews(productId) {
  const response = await fetch(`/api/reviews?product=${productId}`);
  if (!response.ok) throw new Error(`Reviews: ${response.status}`);
  return response.json();
}

button.addEventListener("click", async () => {
  list.replaceChildren();                 // clear what the last request showed
  status.textContent = "Loading…";        // 1. loading
  button.disabled = true;
  try {
    const reviews = await loadReviews(7);
    for (const review of reviews) {
      const item = document.createElement("li");
      item.textContent = review.text;
      list.append(item);
    }
    if (reviews.length === 0) status.textContent = "No reviews yet";     // 3. empty
    else if (reviews.length === 1) status.textContent = "1 review";      // 2. data
    else status.textContent = `${reviews.length} reviews`;
  } catch {
    status.textContent = "Could not load reviews";                       // 4. failed
  } finally {
    button.disabled = false;              // whichever way it went
  }
});

Two details in it are easy to miss. The old rows are cleared before loading, so a failure doesn't leave the last answer on screen looking current. And the empty case is decided only after a successful reply: an empty array means the server answered and there's nothing to show, which deserves its own message rather than the error one.

Replies that arrive out of order

One more thing goes wrong on real networks: responses don't always arrive in the order you asked. If someone searches for shell and then lamp, and the shell reply is slower, it lands last and replaces the right results. The capstone asks you to handle that: remember which request is the latest, and ignore any older reply.

Loading your workspace…