Start learning free

LESSON 47 OF 161 · FRONTEND: TALKING TO AN API

Read the Answer in JavaScript

Practice

In the last lesson the API answered 200, yet the list stayed empty. An answer has a status and a body, which is the content it carries. For /api/products, the body is the list of products, written as JSON text.

response.json() reads the body and turns the JSON into JavaScript values. Here that is an array of product objects, each with a name, a price and a stock. Reading takes time, so response.json() returns a promise too.

When a .then function returns a promise, the next .then waits for it and gets the value inside. That makes a chain, one step per line:

fetch("/api/cart")
  .then((response) => response.json())
  .then((cart) => {
    console.log(cart.items.length);
  });

This logs how many lines the cart has. An arrow function without braces returns its value by itself, so the first .then passes the promise on. Filling an array doesn't change the page, so call render() to draw the page again. No product is written in app.js anymore: they all come from the API.

The check opens the page, then clicks "Add to cart" on the Mug. It must print:

> open the page
  request: GET /api/products -> 200
        text: 8 products
          item: Mug $12
          item: Notebook $7 Out of stock
          … six more products
> click "Add to cart" in "Mug"
    +       item: Mug x 1 $12
    +     text: Total: $12

Your task: chain two .then calls after the fetch. The first reads the body with response.json(). The second puts the array into products and draws the page.


Assignment
Follow the Coding Tutorial to read the products from the API's answer and draw them on the page.


Hint
Write the first .then without braces so it returns response.json(). In the second one, assign data to products, then call render().


STEP 1 OF 4
    Ctrl + Enter to check

    Fetch Read Json 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