I need to update my shopping cart. I am trying to retrieve the information from my old cart, but for some reason, it's not working properly and I keep getting a quantity of 1.
Below is the code for the app.post request:
app.post("/add-to-cart/:id", async (req, res) => {
try {
// fetch your data
const id = req.params.id,
{ data } = await axios.get("http://localhost:4200/products"),
singleProduct = await data.find((product) => product._id === id);
// create/get a cart
let cart;
if (!req.session.cart) {
req.session.cart = cart = new Cart({});
} else {
// req.session does not save the Cart object, but saves it as JSON objects
cart = new Cart(req.session.cart ? req.session.cart : {});
}
console.log("This is variable cart: ",cart)
cart.addProduct(singleProduct);
res.redirect("/");
console.log(req.session)
} catch (error) {
console.log(error);
}
});
There seems to be an issue here:
let cart = new Cart(req.body.cart ? req.body.cart : {});
Here is the output of console.log
:
https://i.sstatic.net/cfj12.png
This is the code for the Cart
:
module.exports = function Cart(oldCart) {
this.productItems = oldCart.productItems || {};
this.totalQty = oldCart.totalQty || 0.00;
this.totalPrice = oldCart.totalPrice || 0.00;
this.addProduct = function(item) {
let storedItem = this.productItems;
if (!storedItem){
storedItem = this.productItems = {item: item, qty: 0, price: 0};
}
else{
storedItem.qty++;
this.totalQty ++;
storedItem = {item: item, qty: storedItem.qty, price: storedItem.price}
storedItem.price = storedItem.item.price * storedItem.qty;
console.log("item from database",storedItem)
this.totalPrice += storedItem.item.price;
}
}
};