Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array containing objects is duplicating them rather than overwriting their values

I’m creating a shopping cart app. When the user changes the quantity of an item, the price of the item should be updated along with it. However, in trying to implement this, I’ve encountered a bug where the items in the shopping cart are being duplicated rather than updated. Any help would be appreciated. Here is my code:

const [cart, setCart] = useState([]);

const handleQuantityChange = (e, product) => {

setCart((prevState) => [
  ...prevState,
  ...prevState.map((item) => {
    if (item.id === product.id) {
      return {
        ...item,
        price: item.originalPrice * e.target.value,
        quantity: e.target.value,
      };
    } else {
      return item;
    }
  }),
]);
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[...prevState, ...prevState.map()] is duplicating your list twice (one is the prevState, one is prevState.map())

You should modify your code like this

const [cart, setCart] = useState([]);

const handleQuantityChange = (e, product) => {

setCart((prevState) => [
  ...prevState.map((item) => {
    if (item.id === product.id) {
      return {
        ...item,
        price: item.originalPrice * e.target.value,
        quantity: e.target.value,
      };
    } else {
      return item;
    }
  }),
]);
}

Another way without prevState but cart state

const [cart, setCart] = useState([]);

const handleQuantityChange = (e, product) => {

  const updatedCart = cart.map((item) => {
    if (item.id === product.id) {
      return {
        ...item,
        price: item.originalPrice * e.target.value,
        quantity: e.target.value,
      };
    } else {
      return item;
    }
  });

  setCart(updatedCart);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading