I'm working on a shopping cart in react by using context. My problem is with changing the state that has an array of objects.
My array will look like this [{itemId: 'ps-5', qty:4}, {itemId: 'iphone-xr', qty:2}]
Here is my code check the comment
export const CartContext = createContext()
class CartContextProvider extends Component {
state = {
productsToPurchase: []
}
addProduct = (itemId)=> {
if (JSON.stringify(this.state.productsToPurchase).includes(itemId)){
// Add one to the qty of the product
this.state.productsToPurchase.map(product=>{
if (product.itemId === itemId){
// This is wrong I have to use setState(), but the syntax is a little bit complex
product.qty = product.qty + 1
}
})
}
else {
this.state.productsToPurchase.push({itemId: itemId, qty: 1})
}
}
render() {
return (
<CartContext.Provider value={{...this.state, addProduct: this.addProduct}}>
{this.props.children}
</CartContext.Provider>
)
}
}
export default CartContextProvider;
You are updating the state directly, but you have to use this.setState to update it,
Live Demo
addProduct = (itemId) => {
this.setState((oldState) => {
const objWithIdExist = oldState.productsToPurchase.find((o) => o.itemId === itemId);
return {
productsToPurchase: !objWithIdExist
? [...oldState.productsToPurchase, { itemId, qty: 1 }]
: oldState.productsToPurchase.map((o) =>
o.itemId !== itemId ? o : { ...o, qty: o.qty + 1 }
)
};
});
};