Easy
Fix React Shopping Cart Component State Synchronization Issue
You're reviewing code for a component that manages a shopping cart. What needs to be fixed?
1<p>function CartItem({ product, quantity, onUpdateQuantity }) {</p><p> const [localQuantity, setLocalQuantity] = useState(quantity);</p><p> </p><p> const incrementQuantity = () => {</p><p> setLocalQuantity(prev => prev + 1);</p><p> onUpdateQuantity(product.id, localQuantity + 1);</p><p> };</p><p> </p><p> const decrementQuantity = () => {</p><p> if (localQuantity > 1) {</p><p> setLocalQuantity(prev => prev - 1);</p><p> onUpdateQuantity(product.id, localQuantity - 1);</p><p> }</p><p> };</p><p> </p><p> const handleQuantityChange = (event) => {</p><p> const newQuantity = parseInt(event.target.value);</p><p> if (newQuantity >= 1) {</p><p> setLocalQuantity(newQuantity);</p><p> onUpdateQuantity(product.id, newQuantity);</p><p> }</p><p> };</p><p> </p><p> const subtotal = product.price * localQuantity;</p><p> </p><p> return (</p><p> <div className="cart-item"></p><p> <img src={product.image} alt={product.name} /></p><p> <div></p><p> <h3>{product.name}</h3></p><p> <p>${product.price}</p></p><p> <div className="quantity-controls"></p><p> <button onClick={decrementQuantity}>-</button></p><p> <input </p><p> type="number"</p><p> value={localQuantity}</p><p> onChange={handleQuantityChange}</p><p> min="1"</p><p> /></p><p> <button onClick={incrementQuantity}>+</button></p><p> </div></p><p> <p>Subtotal: ${subtotal}</p></p><p> </div></p><p> </div></p><p> );</p><p>}</p>