Start learning free

LESSON 58 OF 161 · FRONTEND: TALKING TO AN API

Change and Remove

Practice

The cart lives on the server, so changing it means sending a request. Two more methods do that: PUT replaces something that already exists, and DELETE removes it. The address says which one: /api/cart/1 is the cart line of product 1, the Mug.

A PUT carries the new value as JSON, with the same header as a POST. A DELETE needs only the method. For example, a to-do app could rename task 4, then delete it:

await fetch("/api/todos/4", {
  method: "PUT",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "Buy milk" }),
});
await fetch("/api/todos/4", { method: "DELETE" });

The shop's API answers both with the whole cart, {items, total}. Draw the cart from that answer, not from your own guess: then the screen always shows what the server keeps, even after a reload.

Your page must do this:

click "+" in "Mug x 1"       →  PUT /api/cart/1 {"quantity": 2}  →  200   Mug x 2 $24, Total: $24
reload the page              →  GET /api/cart                    →  200   Mug x 2 $24, Total: $24
click "-" in "Mug x 2"       →  PUT /api/cart/1 {"quantity": 1}  →  200   Mug x 1 $12, Total: $12
click "Remove" in "Mug x 1"  →  DELETE /api/cart/1               →  200   the cart is empty, Total: $0

Your task: the -, + and Remove buttons of a cart line already call changeQuantity(id, quantity) and removeLine(id). Write these two async functions: each sends its request, reads the answer and draws the cart from data.items.


Assignment
Follow the Coding Tutorial to write changeQuantity, which sends a PUT with the new quantity, and removeLine, which sends a DELETE, both redrawing the cart from the server's answer.


Hint
Without a method, fetch sends a GET. A PUT without a body gets 400. And a request whose answer you never draw changes the server, but not the screen.


STEP 1 OF 11
    Ctrl + Enter to check