1

If the object is currently in the array I want to update some value, and if it's not I want to add it to the array. This is the solution I have below, which I don't feel is the best/correct way to do it.

const handleAddToCart = product => {
  const newList = [...cart]
  if (!newList.includes(product)) {
    newList.push(product)
  } else {
    const productIndex = newList.findIndex((obj => obj._id === product._id))
    newList[productIndex].prop = "Some value"
  }
  setCart(newList)
}

Thank you.

A1rPun
  • 16,287
  • 7
  • 57
  • 90
ccrrzz
  • 11
  • 1

2 Answers2

1

You have to be pretty careful here, as there are a few gotchas with object comparison and mutating the state ([...cart] is not sufficient in deep copying cart). You can update the state in a pure fashion as follows, although I would recommend something like Redux for complex state management.

const handleAddToCart = product => {
    const index = cart.findIndex(obj => obj._id === product._id)
    if (index === -1) {
        setCart(cart.concat(product))
    } else {
        setCart([
            ...cart.slice(0, index),
            Object.assign({}, product, { prop: "Some value" }),
            ...cart.slice(index + 1),
        ])
    }
}
iz_
  • 15,923
  • 3
  • 25
  • 40
0
const handleAddToCart = productToAdd => {
    const newList = [...cart];
    const existent = newList.find(product => product.id === productToAdd.id);
    if(existent) {
        existent.prop = "prop";
    } else {
        newList.push(productToAdd);
    }
    setCart(newList);
}
Ken Bekov
  • 13,696
  • 3
  • 36
  • 44
  • Would `existent.prop = productToAdd.prop;` be directly mutating the state? Also, I think you meant `push` instead of `add`. – iz_ May 15 '21 at 01:27
  • @iz_ since we're passing new array to the `setCart()` it's enough to initiate re-rendering. And thanks for noticing `add` ) – Ken Bekov May 15 '21 at 01:31
  • I'm not very familiar with React internals, but this question https://stackoverflow.com/q/37755997 seems to suggest that you should avoid mutating state even if it does not cause any immediate problems. – iz_ May 15 '21 at 01:35
  • @iz_ generally it's a good suggestion. But it depends on structure of component. And it's really applicable to redux reducers. I just answered the question of the topic. – Ken Bekov May 15 '21 at 01:43