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.