Now I can only add products using one price. In db I have two prices and different colors. It needs to work like this, the first price is applied to the first color, the second price to all others colors
/src/app.js
const {getData} = require('./db/db');
const products = getData();
const [cartItems, setCartItems] = useState([]);
const onAdd = (product) => {
const exist = cartItems.find((x) => x.id === product.id);
if (exist) {
setCartItems(
cartItems.map((x) =>
x.id === product.id ? {...exist, qty: exist.qty + 1} : x
)
);
} else {
setCartItems([...cartItems, {...product, qty:1}])
}
};
/src/components/cart.jsx
function Cart({cartItems, onCheckout}) {
const totalPrice = cartItems.reduce((a, c) => a + c.price[0] * c.qty, 0);
return (
<div className='cart_container'>
<br/>
<Button
title={`${cartItems.length === 0 ? "Cart is empty" : "Cart" + '\n' + "Total Price: " + totalPrice} `}
type={"checkout"}
disable={cartItems.length === 0 ? true : false}
onClick={onCheckout}
/>
</div>
);
}
you can go about doing it this way:
const firstColor = "grey" // for example
const totalPrice = cartItems.reduce((a, c) =>{
const price = c.color == firstColor ? c.price[0] : c.price[1]
return a + price * c.qty :
}, 0);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.