So what I wanted to do was to also calculate the unit price according to what number was entered. I was already able to update the quantity of the product and then calculate its unit price and also its total amount.
My problem now is how can I also allow the user to enter the quantity of the product. And also still retain the functionality to increase and decrease the product.
I have recreated this in codesandbox: https://codesandbox.io/s/add-to-cart-sampled-2-with-table-efqrhd?file=/src/Cart.js
const Cart = ({ cartItems, handleCartClearance, handleRemove, handleAdd }) => {
const [inputQty, setInputQty] = useState(0);
console.log(cartItems, "items");
const totalAmount = cartItems.reduce(
(price, item) => price + item.quantity * item.price,
0
);
const handleSubmit = (e) => {
e.preventDefault();
console.log(cartItems, "order");
};
console.log(
"test",
cartItems.reduce((prev, item) => {
if (!prev[item.id]) prev[item.id] = { ...item, nest: [] };
prev[item.id].nest.push({ ...item });
return prev;
}, {})
);
return (
<div>
<form onSubmit={handleSubmit}>
Order page
{cartItems.length >= 1 && (
<Button onClick={handleCartClearance}>Clear Orders</Button>
)}
{cartItems.length === 0 && <div>No Items in the cart</div>}
<div>
{Object.entries(
cartItems.reduce((prev, item) => {
if (!prev[item.id]) prev[item.id] = { ...item, nest: [] };
prev[item.id].nest.push(item);
return prev;
}, {})
).map(([id, obj], idx) => (
<TableContainer key={id + obj.color} component={Paper}>
<Table aria-label="simple table">
<TableHead>
<TableRow>
<TableCell align="center">
Product Name: {obj.name + " " + obj.size}
</TableCell>
<TableCell colspan={3}></TableCell>
</TableRow>
<TableRow>
<TableCell>Color</TableCell>
<TableCell>Qty</TableCell>
<TableCell></TableCell>
<TableCell>Unit Price</TableCell>
</TableRow>
</TableHead>
<TableBody>
{obj.nest.map((nest, idx) => (
<TableRow key={idx}>
<TableCell>{nest.color}</TableCell>
<TableCell>
<input
style={{ width: "1rem" }}
value={nest.quantity}
/>
</TableCell>
<TableCell align="right">
<IconButton
onClick={(e) =>
handleAdd(
nest.id,
nest.prodName,
nest.price,
nest.size,
nest.cat,
nest.color
)
}
>
<AddIcon color="success" />
</IconButton>
<IconButton onClick={() => handleRemove(nest)}>
<RemoveIcon />
</IconButton>
</TableCell>
<TableCell>
{Number(nest.quantity) * Number(nest.price)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
))}
<div>
<b>Total Amount :{totalAmount}</b>
</div>
{cartItems.length >= 1 && <Button type="submit">Save Order</Button>}
</div>
</form>
</div>
);
};
export default Cart;