Skip to main content
Frontend tutorial

7.1. Fetch using await

Here is a small ShippingBoard: a store that loads the ramps in init, and an App that shows them. The store already waits for api.getRamps(), but the API still answers with two ramps written by hand. Time to ask the server.

In /api.ts, add the base URL and the shape of the server's JSON, then replace getRamps:

const BASE_URL = 'https://raw.githubusercontent.com/adam-zielonka/shippingboard-lite/bdd5494f80b7/src/api/';

type RampResponse = {
ramp_id: string;
description: string;
};

export class API {
async getRamps(): Promise<Ramp[]> {
const response = await fetch(BASE_URL + 'RAMPS.json');

if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}

const json = await response.json() as RampResponse[];

return json.map(r => new Ramp(r.ramp_id, r.description));
}
}

With await, fetch waits for the server's answer, and response.json() for the body. A 404 is still an answer, so fetch doesn't fail on it. We check response.ok and throw: an empty list would tell the user there are no ramps, and that isn't true.

The JSON uses the server's field names. RampResponse describes them, and map turns every record into our Ramp. In production I'd validate this; here we trust our own JSON.

Need a hint?
  • response.json() returns a promise too, so it needs its own await.
  • The server calls the id ramp_id: new Ramp(r.ramp_id, r.description).

The two hand-written ramps are gone. Now you see all seven, A to G, straight from GitHub.

Work locally

You need Node.js 24, pnpm and Git (how to set them up). Clone this step’s starting code:

git clone --depth 1 \
--branch lesson-07-01-await-start-v6 \
https://github.com/adam-zielonka/frontend-tutorial.git \
07-01-await
cd 07-01-await
pnpm install --frozen-lockfile
pnpm dev

To keep your own commits: git switch -c my-work.

Browse the source on GitHub (opens in a new tab)

Bring your browser edits

Choose Download my files in the ⋯ menu. It saves the lesson’s files as JSON. Stop the local server with Ctrl+C, copy the download into the project folder and run:

node import-draft.mjs ./07-01-await-my-files.json
pnpm dev

The import replaces the project’s exercise files, so commit or back up local edits first.

Loading this step’s code…
Starting the live preview…