Start learning free

LESSON 88 OF 161 · FRONTEND: REACT EFFECTS AND DATA

Change Data on the Server

Practice

So far the page only read from the API, with GET. To change data on the server, it sends another method: POST means "add this". A POST carries a body, the data written as JSON text, and a Content-Type header that tells the server the body is JSON.

The second argument of fetch is an object of options. This POST would place an order:

const response = await fetch("/api/orders", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ email: "you@example.com" }),
});

The shop's POST /api/cart answers with the whole cart, { items, total }, so the page can put items straight into its cart state. And since the cart now lives on the server, the page asks GET /api/cart once, when it opens: a reload shows the same cart.

Your page must do this:

> open the page
  GET /api/cart  →  200   Your cart is empty
> click "Add to cart" in "Mug"
  POST /api/cart {"product_id": 1, "quantity": 1}  →  201   Cart (1), Mug × 1 $12
> click "Add to cart" in "Mug"
  POST /api/cart {"product_id": 1, "quantity": 1}  →  201   Cart (2), Mug × 2 $24
> reload the page
  GET /api/cart  →  200   Mug × 2 $24

Your task: in src/App.jsx, make addToCart send the POST and give the answer's items to setCart. Then load the cart with GET /api/cart in an effect that runs once.


Assignment
Follow the Coding Tutorial to send POST /api/cart from addToCart and to load the cart from the server when the page opens.


Hint
Without a method, fetch sends a GET. A body is text: JSON.stringify turns an object into JSON.


STEP 1 OF 12
    Ctrl + Enter to check