Start learning free

LESSON 60 OF 161 · FRONTEND: TALKING TO AN API

One Helper for Every Call in JavaScript

Practice

Your page talks to the API from seven functions, and each one repeats the same work: build the address, add the JSON header when there is a body, read the JSON, check response.ok. A helper function does that work in one place, and every call becomes one line, like const data = await api("/cart");.

Your page starts broken: its functions already call api, which doesn't exist yet. In loadProducts that call throws a ReferenceError, an error with no status, so the catch shows the network message, "Can't reach the shop", and 0 products. Nothing is wrong with the network; the page works again once you write api.

A parameter can have a default: with function greet(name = "friend"), a call with no argument gets "friend". The helper's options = {} works the same way, so a GET can pass only the path.

fetch does not throw when the server says no. The helper does: it throws an Error made from the server's message, with the status attached, so every catch knows what went wrong. For example:

const error = new Error("Too many tries");
error.status = 429;
throw error;

An error with a status means the server answered; one without a status means the network failed. Your page must do this:

open the page                   →  GET /api/products?page=1&per_page=3  →  200   3 products, Load more
click "Load more"               →  GET /api/products?page=2&per_page=3  →  200   6 products
click "Add to cart" in "Lamp"   →  POST /api/cart {"product_id": 3, "quantity": 1}  →  201   Lamp x 1 $29
click "Add to cart" in "Lamp"   →  the same POST  →  409   under the Lamp: Only 1 left
click "Remove" in "Lamp x 1"    →  DELETE /api/cart/3  →  200   the cart is empty
the API fails, choose "Office"  →  GET /api/products?category=office&page=1&per_page=3  →  500
                                   The shop has a problem, try again later

Your task: write async function api(path, options = {}). It fetches "/api" + path, adds the JSON header when there is a body, reads the JSON, throws an Error with the server's message and status when response.ok is false, and returns the data. Then make removeLine and loadMore use it too.


Assignment
Follow the Coding Tutorial to write the api helper and send every call of the page through it.


Hint
Check response.ok after reading the JSON: the server's reason is in data.error. Set error.status before the throw, because nothing after a throw runs.


STEP 1 OF 12
    Ctrl + Enter to check

    Fetch Api Helper 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