Cannot get the value of an old (previous) cart

I want to “overwrite” my cart. So I get the information I want but the problem is I can’t get the information of my old cart. I don’t get it how it cannot be properly retrieved. And whole the time I’m getting quantity of 1.

Here is 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);
  }
});

It seems that something is wrong here: let cart = new Cart(req.body.cart ? req.body.cart : {});

So this is the console.log output:

enter image description here

This is the Cart code:

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;
        }
    }

    };

Answer

You can use the express-session package to store session data on the server-side per session/user:

const session = require("express-session");

app.use(session({
  secret: "some secret"
}));

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) {
      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 = cart;
    cart.addProduct(singleProduct);
    res.redirect("/");
  } catch (error) {
    console.log(error);
  }
});

Then, if the client needs to fetch the cart data, you can create a path for that:

app.get("/get-cart", (req, res) => {
  const cartData = req.session.cart || {};
  res.send(JSON.stringify(cartData));
});

In the code you provided, I also noticed some issues with your Cart class.

When setting your default values of totalQty and totalPrice, you use oldCart.totalQty || oldCart.totalQty==0.00, which will set it to the totalQty, or a boolean which checks if the totalQty is 0.00.

Also, your addProduct function checks if storedItem is falsey/truthy, which it will always be truthy (default value = {}), result in your logic using an empty object for your item, and resulting in prop of undefined errors.

To fix this: do something like:

module.exports = function Cart(oldCart) {
  this.productItems = oldCart.productItems || {};
  this.totalQty = oldCart.totalQty || 0;
  this.totalPrice = oldCart.totalPrice || 0.00;

  this.addProduct = function(item) {
    let storedItem = this.productItems;
    if (!storedItem.hasOwnProperty("item")) {
      storedItem = this.productItems = {item: item, qty: 1, price: item.price};
      this.totalQty = 1;
      this.totalPrice = item.price;
    } else {
      storedItem = {item: item, qty: storedItem.qty, price: storedItem.price};
      console.log("STORED ITEM: ", storedItem);
      this.productItems = storedItem;
      storedItem.qty++;
      storedItem.price = storedItem.item.price * storedItem.qty;
      this.totalQty++;
      this.totalPrice += storedItem.item.price;
    }
  }
}