I have an object array that looks like this
index:
product: data: id:
quantity:
I have a shop that when items are added they need to be added to the cart. If the user adds the same object to the cart multiple times I just need the quantity of that item to update.
For some reason when adding the same item to the cart the quantity gets updated correctly the first time. The second time I add the same item to the cart my temp variable that copies the useState array becomes undefined and my quantity value becomes NaN. Using .slice() yielded the same results.
basically:
I add the first item to the cart. I add the same item to the cart with another quantity it updates fine. If add it again the temp var is undefined and my value is now NaN.
const [cart, setCart] = React.useState([])
const addToCart = (data) => {
const index = cart.findIndex(ele => ele.product.data.id === data.product.data.id)
if (index !== -1) {
let temp = [...cart]
temp[index] = { ...temp[index], quantity: (data.quantity.value + temp[index].quantity.value) }
setCart([...temp])
}
else {
setCart([...cart, data])
}
}
2
Answers
I think it is one of the most common problems. Please read this documentation.
I think it may help:
Also you can use immer if you want update your object or array state directly.
Your data structure is inconsistent between your calls to
addToCart
.It looks like your base state is an Array of objects with at least the following structure:
But when you call
addToCart
, this line of code is changing the structure of your cart item:We could re-format that so it’s a little easier to read:
So when you call
addToCart
again, the value from your state now looks like this:Compare that to
cartItem
above; you’ll see that the structure forquantity
is now different.What that problematic line should read is this:
Try that and see if it helps!