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.
1Ask the bakery's server
Get the menu with fetch.
What to type What it does You see fetch("/api/menu").then((r) => r.json()).then((menu) => draw(menu));Ask with fetch GET /api/menu · 200 2Wait for the answer
Read it top to bottom with await.
What to type What it does You see const r = await fetch("/api/menu");Wait for the server · const menu = await r.json();Wait for the JSON 4 cakes on the menu 3Show that it's loading
Never leave a blank screen.
What to type What it does You see status.textContent = "Loading the menu…";Say it's loading 4 cakes on the menu 4When the server has a bad day
Check the answer before using it.
What to type What it does You see if (!r.ok) {Check r.ok · status.textContent = "Sorry, the menu didn't load.";Say sorry GET /api/menu · 500 5No signal on the train
Catch a lost connection.
What to type What it does You see } catch (e) {Catch a lost connection · status.textContent = "No connection. Check your Wi-Fi.";Say what happened GET /api/menu · no connection 6A Try again button
Let people ask once more.
What to type What it does You see again.hidden = false;Show Try again on a failure · again.hidden = true;Hide it when loading · status.classList.remove("bad");Clear the red · 7Send an order
Give the server new data with POST.
What to type What it does You see method: "POST",Send with POST · headers: { "Content-Type": "application/json" },Say it's JSON · body: JSON.stringify(order),Send the order as text POST /api/orders · 201 8Cancel an order
Remove data with DELETE.
What to type What it does You see await fetch("/api/orders/" + id, { method: "DELETE" });Ask to delete 1 order left 9The menu, even offline
Keep a copy on the phone.
What to type What it does You 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 old 4 cakes on the menu 10On your own: the bus stop screen
Fetch, wait, and handle trouble.
What to type What it does You see status.textContent = "Loading…";Say it's loading · const r = await fetch("/api/buses");Fetch with await · if (!r.ok) {Check the answer 3 buses due