i have this code:
const [cart, setCart]=useState([{}]);
function AddToCart(item){
setCart((prevItem)=>{
if (prevItem.find(cartItem => cartItem.productId ===item.productId)){
console.log('yes')
let objIndex= prevItem.findIndex(stuff => stuff.productId ===item.productId)
prevItem[objIndex].quantity = (prevItem[objIndex].quantity +1)
return [...prevItem]
}
console.log('no');
return [...prevItem, item];
})
}
It behaves exactly as I need it to when I call it, everytime I click, the same item stays the same in array but the quantity increases
const Item = {
productId: 8,
name:'Kettle',
price: 10
};
When i render:
<button onClick={() => AddToCart(Item, Item.quantity=1)} >test</button>
But when I use the same code in a .map function with all the items, I notice the quantity never goes above 2 and I cannot add additional items to get the quantity to increase:
{shopData.map((data, index) => (
<div className='grid-item-1'>
<Card style={{ width: '18rem' }} key={data.index}>
<Card.Img variant="top" src={data.imageUrl} />
<Card.Body>
<Card.Text className='card-title'>
{data.name}
</Card.Text>
<Card.Text className='card-price'>
{data.price}
</Card.Text>
<button className='add-cart-btn' >Add to Cart </button>
<button onClick={() => AddToCart(data, data.quantity=1)} className='add-item-btn' >Add Items </button>
</Card.Body>
</Card>
</div>
))}
Can someone explain why this is the case?
I created the function and used it to increment quantity, which works completely fine. Using it in a .map function however, quantity never goes above 2.

