Start learning free

LESSON 27 OF 58 · FULL-STACK: CART AND CHECKOUT

Change and Remove Lines in JavaScript

Practice

On the cart page each line has three buttons: +, − and Remove. They don't add to a line the way POST /api/cart does: they set it. For a + on a Mug line of 1, the given CartContext.jsx sends PUT /api/cart/1 {"quantity": 2}: the product's id is in the path, and the body holds the line's new quantity.

A part of the path that starts with : is a route parameter: Express puts its value in req.params. For example, a route for one product (not part of this lesson):

app.get("/api/products/:id", (req, res) => {
  const product = db.prepare("SELECT * FROM products WHERE id = ?").get(req.params.id);
  res.json(product);
});

The PUT route checks the new quantity against the stock (409, "Only 1 left"). A quantity of 0 deletes the line; any other is saved with INSERT OR REPLACE. DELETE /api/cart/:productId removes the line. Both answer the whole cart, so the page shows it as it is.

The check opens Ana's cart with a Mug and a Lamp (Total: $41) and clicks:

+ on Mug        →  PUT /api/cart/1 {"quantity": 2}  →  200  Mug × 2 $24, Total: $53, Cart (3)
+ on Lamp       →  PUT /api/cart/3 {"quantity": 2}  →  409  alert: Only 1 left
Remove on Lamp  →  DELETE /api/cart/3               →  200  Total: $24, Cart (2)
− on Mug        →  PUT /api/cart/1 {"quantity": 1}  →  200  Mug × 1 $12, Total: $12
− on Mug        →  PUT /api/cart/1 {"quantity": 0}  →  200  Your cart is empty, Total: $0

Your task: in server/app.js, the start of the PUT route is given: it finds the product or answers 404, and it ends with the cart. Add the stock check, the delete for a quantity of 0 and the save for any other quantity; then write the DELETE route.


Assignment
Follow the Coding Tutorial to finish PUT /api/cart/:productId and to write DELETE /api/cart/:productId, so the cart page's +, − and Remove buttons work.


Hint
The DELETE query needs two placeholders, user_id and product_id, so a user only ever removes their own line. In the PUT route they are req.user.id and product.id; in the DELETE route the product's id comes from req.params.productId.


STEP 1 OF 9
    Ctrl + Enter to check

    Fscart Change Lines 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