const [cartItems, setcartItems] = useState([] as Product[]);
const addItemToCart = (product: Product) => {
setcartItems((preCartItems) => {
const updatedcart = [...preCartItems];
if(!updatedcart.length)
updatedcart.push(product)
// updatedcart[0].price original value 1
updatedcart[0].price = updatedcart[0].price 1 ;
console.log(updatedcart[0].price); // prints 2
console.log(updatedcart); // printed object is saying price value 3
return updatedcart;
});
};
I am unable to understand how the value is incremented automatically by 1 and why is the value on the object giving a different output compared to the value accessed by the dot operator
CodePudding user response:
The problem is that you're mutating your state within the setcartItems.
Doing const updatedcart = [...preCartItems]; is not copying the objects in preCartItems, it's just spreading the reference of the same objects in a new array.
Then you're mutating the object here updatedcart[0].price = updatedcart[0].price 1 ;.
This will lead to two different versions of the state, hence the inconsistent result.
If you want to copy the objects you should do
const updatedcart = preCartItems.map(item => ({ ...item }));
This returns a new array of new objects and you can do any operation you want on them. This way of copying an array of objects is also shallow, it only works for 1 depth level, if you want to copy also nested objects you need a more robust function.
