Save it and fetch it

Cheat sheet · Level 2

Talk to a server

Every command and idea of this level on one page: what to type, what it does, and what you see.

Take the level exam
  1. 1Ask the bakery's server

    Get the menu with fetch.

    What to typeWhat it doesYou see
    fetch("/api/menu").then((r) => r.json()).then((menu) => draw(menu));Ask with fetchGET /api/menu · 200
  2. 2Wait for the answer

    Read it top to bottom with await.

    What to typeWhat it doesYou see
    const r = await fetch("/api/menu");Wait for the server·
    const menu = await r.json();Wait for the JSON4 cakes on the menu
  3. 3Show that it's loading

    Never leave a blank screen.

    What to typeWhat it doesYou see
    status.textContent = "Loading the menu…";Say it's loading4 cakes on the menu
  4. 4When the server has a bad day

    Check the answer before using it.

    What to typeWhat it doesYou see
    if (!r.ok) {Check r.ok·
    status.textContent = "Sorry, the menu didn't load.";Say sorryGET /api/menu · 500
  5. 5No signal on the train

    Catch a lost connection.

    What to typeWhat it doesYou see
    } catch (e) {Catch a lost connection·
    status.textContent = "No connection. Check your Wi-Fi.";Say what happenedGET /api/menu · no connection
  6. 6A Try again button

    Let people ask once more.

    What to typeWhat it doesYou see
    again.hidden = false;Show Try again on a failure·
    again.hidden = true;Hide it when loading·
    status.classList.remove("bad");Clear the red·
  7. 7Send an order

    Give the server new data with POST.

    What to typeWhat it doesYou see
    method: "POST",Send with POST·
    headers: { "Content-Type": "application/json" },Say it's JSON·
    body: JSON.stringify(order),Send the order as textPOST /api/orders · 201
  8. 8Cancel an order

    Remove data with DELETE.

    What to typeWhat it doesYou see
    await fetch("/api/orders/" + id, { method: "DELETE" });Ask to delete1 order left
  9. 9The menu, even offline

    Keep a copy on the phone.

    What to typeWhat it doesYou see
    localStorage.setItem("menu", JSON.stringify(menu));Save a copy when it arrives·
    const saved = localStorage.getItem("menu");Read the copy offline·
    draw(JSON.parse(saved));Draw the copy·
    status.textContent = "Offline: this is the last menu you saw.";Say it may be old4 cakes on the menu
  10. 10On your own: the bus stop screen

    Fetch, wait, and handle trouble.

    What to typeWhat it doesYou see
    status.textContent = "Loading…";Say it's loading·
    const r = await fetch("/api/buses");Fetch with await·
    if (!r.ok) {Check the answer3 buses due