I am using add to cart function and I am successfully getting the item in my cart on the first click. It just won't increment when I add multiple objects in the cart. It is just displaying one item on a click. The length and the qty of the array always remains 1.
const Card = (props) => {
const { product } = props;
const [isActive, setIsActive] = useState(true);
const [quantity, setQuantity] = useState(1);
const [cart, setCart] = useState([]);
const handleDecrement = () => {
if (quantity > 1) {
setQuantity((prevCount) => prevCount - 1);
} else if (quantity === 1) {
setIsActive(true);
}
};
const handleIncrement = () => {
if (quantity < 5) {
setQuantity((prevCount) => prevCount + 1);
addToCart(product);
}
};
const addToCart = (product) => {
const exist = cart.find((x) => x.id === product.id);
if (exist) {
setCart(
cart.map((x) =>
x.id === product.id ? { ...exist, qty: exist.qty + 1 } : x
)
);
} else {
setCart([...cart, {...product, qty: 1}])
}
};
console.log(cart);
return (
<>
<div className="card">
<div className="product-details">
<div className="img-container">
<img src={product.img} alt={product.title} />
</div>
<div className="data-container">
<div className="title">{product.title}</div>
<div className="subheading">{product.subheading}</div>
<div className="price">{product.price}</div>
</div>
</div>
<div className="button">
{isActive && (
<button
onClick={() => {
setIsActive(!isActive);
addToCart(product);
}}
>
ADD
</button>
)}
{isActive === false ? (
<div className="inc">
<span onClick={handleDecrement}>-</span>
<span> {quantity} </span>
<span onClick={handleIncrement}>+</span>
</div>
) : null}
</div>
</div>
<Footer cart={cart}/>
</>
);
};
Can someone tell what am I doing wrong? I've been stuck on it for a while now.