This thing works on server side fine for me, session successfully adds data in a cart as it should. But on client side (I'm using axios) the session is constantly being recreated. By recreating the data I mean for example when I try to add more items in cart, whole the time quantity is still 1 and it is being recreated constantly with last item.
This is file where I use session:
app.use(session({
secret: "hideSession",
resave: true,
saveUninitialized: true,
cookie: {
sameSite: true,
httpOnly: false,
}
}));
Whole add_to_cart route request:
app.post("/add_to_cart/:name", async (req, res) => {
let db = await connect();
let cursor = await db.collection("products").find({})
let finalData = await cursor.toArray();
const name= req.params.name;
const singleDrink = await finalData.find((product) => product.name === name);
let cart;
if (!req.session.cart) req.session.cart = cart = new Cart({});
else cart = new Cart(req.session.cart);
req.session.cart = cart;
cart.addDrink(singleDrink);
console.log(req.session.cart,req.session.cookie)
res.send(cart);
});
client side using axios:
let Cart = {
addToCart(name){
return Service.post(`/add_to_cart/${name}`)
}
}
client side passing function from axios:
async sendCartData(name){
Cart.addToCart(name);
}
And button:
<p @click="sendCartData(item.name)" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</p>
This is Cart file:
module.exports = function Cart(oldCart) {
this.products = oldCart.products || {};
this.totalQty = oldCart.totalQty || 0;
this.totalPrice = oldCart.totalPrice || 0.00;
this.addDrink = function(item) {
let storeItem = this.products;
if (!storeItem.hasOwnProperty("item")) {
storeItem = this.products = {item: item};
this.totalQty = 1;
this.totalPrice = parseFloat(item.price);
} else {
storeItem = {item: item};
this.products = storeItem;
Object.defineProperties(storeItem, {
currentQty: {
enumerable: false,
writable: true
},
price: {
enumerable: false,
writable: true
}
},
);
storeItem.currentQty++;
storeItem.price = parseFloat(storeItem.item.price * storeItem.currentQty);
this.totalQty++;
this.totalPrice += parseFloat(storeItem.item.price);
}
}
}

