I'm trying to make cart items to stack dynamically every time on function call: addProduct(). The data which I want to work with was captured successfully but the problem is that on each function call the quantity always remains 1.
This is the logic which I implemented:
module.exports = function Cart(oldCart) {
this.productItems = oldCart.productItems || {};
this.totalQty = oldCart.totalQty || oldCart.totalQty==0.00;
this.totalPrice = oldCart.totalPrice || oldCart.totalPrice==0.00;
this.addProduct = function(item, id) {
//let storedItem = this.productItems = {item: item, qty: 0, price: 0};
/*Using this storedItem qty: 0, price: 0 for testing*/
if (!storedItem){
storedItem = this.productItems = {item: item, qty: 0, price: 0};
}
storedItem = {item: item, qty: storedItem.qty, price: storedItem.price}
storedItem.qty++;
storedItem.price = storedItem.item.price * storedItem.qty;
this.totalQty ++;
this.totalPrice += storedItem.price;
//this.productItems += storedItem;
console.log("Product items: ",this.productItems)
}
this.generateArray = function () {
let arr = [];
for (let id in this.productItems) {
arr.push(this.productItems);
}
return arr;
}};
When I remove line: let storedItem = this.productItems = {item: item, qty: 0, price: 0}; the result remains NaN. So how to solve this problem? Because the items are still at the quantity of 1 no matter how many API calls do I make.
Here is my app.post call:
app.post('/add-to-cart/:id', async (req, res) => {
try {
let id = req.params.id;
let cart = new Cart(req.body.cart ? req.body.cart : {});
const { data } = await axios.get('http://localhost:4200/products');
const singleProduct = await data.find((product) => product._id === id)
cart.addProduct(singleProduct, singleProduct._id)
req.body.cart = cart;
res.redirect('/');
console.log("console log cart",cart);
console.log(req.body);
}
catch (error){
console.log(error)
}
});
Here is my console.log result (every time the same):
How to solve this issue?
