I'm building a basic shopping cart example which has 2 buttons, addtoCart that calculates total amount and Quantity which will update the qty. But when I click on it, quantities of all products are updated at once. How can I do it for specific product?
import React,{useContext, useState, useReducer, useEffect} from 'react'
const Wishlist=()=>{
const product=[
{ name: "Apple", price: 10 },
{ name: "Banana", price: 20 },
{ name: "Cherry", price: 30 }
]
const [total,setTotal]=useState(0)
const [qty,setQty]=useState(1)
const handleClick = e => {
setTotal(prevState=>prevState+e)
};
const handleQty=e=>{
setQty(prevState=>prevState+1)
}
return(
<div>
{product.map((p)=>
<li key={p.name}>{p.name}{p.price}
<button onClick={()=>handleClick(p.price)}>Add to cart</button>
<button onClick={()=>handleQty(p)}>x{qty}</button>
</li>)
}
Price: {total}
</div>
)
}
export default Wishlist
Is there a way where multiple clicks on Add to Cart button updates individual quantity as well and calculates total amount? I can't seem to figure out.
[EDIT]
Now I've added a unit property as well, still all quantities are updated at once. Here's the code:
import React,{useContext, useState, useReducer, useEffect} from 'react'
const Wishlist=()=>{
const product=[
{ name: "Apple", price: 10,unit:1},
{ name: "Banana", price: 20,unit:1 },
{ name: "Cherry", price: 30,unit:1 }
]
const [total,setTotal]=useState(0)
const [qty,setQty]=useState(1)
const handleClick=e=>{
setTotal(prevState=>prevState+e.price),
setQty(e.unit+1)
console.log(e)
};
return(
<div>
{product.map((p)=>
<li key={p.name}>{p.name}{p.price}
<button onClick={()=>handleClick(p)}>Add to cart </button>
{qty}
</li>)
}
Price: {total}
</div>
)
}
export default Wishlist
question from:
https://stackoverflow.com/questions/65646707/how-to-change-individual-cart-quantity-in-react 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…