Start learning free

LESSON 49 OF 161 · FRONTEND: TALKING TO AN API

While You Wait in JavaScript

Practice

A request takes time. While the answer to GET /api/products is on its way, your page already shows 0 products and an empty list. A visitor could think the shop has nothing to sell. A loading message tells them the page is still waiting.

The trick is where the lines go. await pauses only your function, not the page. So text you set before the request stays on the screen for the whole wait, and text you clear after the answer goes away when the products arrive. Here is the same idea for a list of categories:

note.textContent = "Loading categories…";
const response = await fetch("/api/categories");
note.textContent = "";

index.html now has an empty paragraph <p id="message"> above the count. An empty paragraph shows nothing, so the check doesn't print it. Under Check, your page must show:

> open the page
  request: GET /api/products ...
  screen while waiting:
    text: Loading products…
    text: 0 products
    list (empty)
  answer: GET /api/products -> 200
  screen changes:
    -  text: Loading products…
    -  text: 0 products
    +  text: 8 products
    +  item: Mug $12 …

Your task: select #message into a constant message, make loadProducts show "Loading products…" before it asks, and clear the message once the answer has been read.


Assignment
Follow the Coding Tutorial to show a loading message while the page waits for the shop's API, and remove it when the products arrive.


Hint
Order matters: the Loading line goes above the await fetch line, and the empty-string line goes below the await response.json() line.


STEP 1 OF 3
    Ctrl + Enter to check

    Fetch Loading 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