Start learning free

LESSON 128 OF 161 · FRONTEND: FRONTEND WITH AI

The AI Changed State in Place in JavaScript

Practice

An AI assistant wrote the shop's addToCart in src/App.jsx. It changes the cart, then hands it to setCart:

function addToCart(product) {
  const existing = cart.find((item) => item.id === product.id);
  if (existing) {
    existing.quantity = existing.quantity + 1;
    setCart(cart);
    return;
  }
  cart.push({ id: product.id, name: product.name, price: product.price, quantity: 1 });
  setCart(cart);
}

A setter compares the new value with the old one, and draws only if it is a different value. setCart(cart) hands React the same array it already has, only changed inside, so React sees nothing new and doesn't draw. The visitor clicks "Add to cart" and the cart still says "Your cart is empty". Later, when something else draws the page, like typing a note, the changed cart suddenly appears.

State must be replaced, not changed in place: give the setter a new array or a new object. For example, adding a tag: setTags([...tags, "sale"]), or renaming a user: setUser({ ...user, name: "Ana" }).

The check adds the Mug twice, then the Teapot, then types a note. Your page must show:

> click "Add to cart" in "Mug"
  screen changes:
    -     text: Your cart is empty
    +     text: Total: $12
    +     list
    +       item: Mug × 1 $12
> click "Add to cart" in "Mug"
  screen changes:
    -     text: Total: $12
    +     text: Total: $24
    -       item: Mug × 1 $12
    +       item: Mug × 2 $24
> click "Add to cart" in "Teapot"
  screen changes:
    -     text: Total: $24
    +     text: Total: $46
    +       item: Teapot × 1 $22
> type "Ring the bell" into "Note for the shop"
  screen changes:
    -   field "Note for the shop": ""
    +   field "Note for the shop": "Ring the bell"

Your task: in src/App.jsx, rewrite addToCart. Find the product in the cart. If it is there, give setCart a map of the cart where this item is a copy with quantity + 1, and return. Otherwise, make a new line with quantity: 1 and give setCart a new array: the cart's items, then the line.


Assignment
Follow the Coding Tutorial to rewrite addToCart so that every change to the cart gives setCart a new array.


Hint
[...cart, line] and cart.map(…) both make new arrays, and { ...item, quantity: item.quantity + 1 } makes a new object. push, and = on an item's field, change the old ones.


STEP 1 OF 6
    Ctrl + Enter to check

    Aiui Mutated State 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