Start learning free

LESSON 76 OF 161 · FRONTEND: REACT COMPONENTS AND STATE

Change One Item

Practice

Now the cart must handle a product that is already in it. A second click on Mug shouldn't add a second Mug line: it should raise that line's quantity. In state, you never change an object or an array in place. You make a new array, with a copy of the one line that changes.

map makes a new array with one entry per item: return the item itself to keep it, or a copy to change it. In { ...item, quantity: 3 }, the spread copies every property, and the one written after it replaces the old value. filter makes a new array without the items its test says false for, and some answers true when its test is true for at least one item. Here is the idea on a to-do list:

function finish(id) {
  const next = tasks.map((task) => {
    if (task.id !== id) return task;
    return { ...task, done: true };
  });
  setTasks(next);
}

const minutes = tasks.reduce((sum, task) => sum + task.minutes, 0);

The count and the total aren't stored: reduce computes them from cart on every draw. The count adds up the quantities, so Mug × 2 and Lamp × 1 make Cart (3), even though the array has 2 lines.

The check adds Mug, Lamp and Mug again, then removes Mug:

> open the page                  →  text: Cart (0)  …  text: Your cart is empty
> click "Add to cart" in "Mug"   →  + text: Cart (1)  + item: Mug × 1 $12   + text: Total: $12
> click "Add to cart" in "Lamp"  →  + text: Cart (2)  + item: Lamp × 1 $29  + text: Total: $41
> click "Add to cart" in "Mug"   →  + text: Cart (3)  + item: Mug × 2 $24   + text: Total: $53
> click "Remove Mug"             →  + text: Cart (1)  - item: Mug × 2 $24   + text: Total: $29

Your task: in src/App.jsx, compute count and total, show Cart (…), give the Cart its lines, the total and onRemove. In addToCart, raise the quantity of a product already in the cart with map and a copy, and write removeFromCart with filter.


Assignment
Follow the Coding Tutorial to change one line of the cart with a copy, remove a line with filter, and compute the count and the total during the draw.


Hint
In the map, return the item unchanged when its id isn't the product's id: otherwise every line goes up by one.


STEP 1 OF 12
    Ctrl + Enter to check