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.

2
  • Is there some unique identifier for each object? If not, then you will need to do a deep comparison of the objects. Commented May 15, 2021 at 1:10
  • Each object in the Array has a unique _id property. Commented May 15, 2021 at 1:11

2 Answers 2

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),
        ])
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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);
}

4 Comments

Would existent.prop = productToAdd.prop; be directly mutating the state? Also, I think you meant push instead of add.
@iz_ since we're passing new array to the setCart() it's enough to initiate re-rendering. And thanks for noticing add )
I'm not very familiar with React internals, but this question stackoverflow.com/q/37755997 seems to suggest that you should avoid mutating state even if it does not cause any immediate problems.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.