Search code examples
javascriptnode.jsexpressexpress-session

Using express-session variable as type array


I am creating an e-commerce type site with shopping cart functionality.

When a Customer adds product to cart, I need to add the data of the product into an array in the session variable.

I tried like this:

 router.post('/addtocart', authCheck.login, async(req, res) => {
    // console.log(req.body)

    req.session.cart = []
    
    let doc = {
        ...req.body
    }
    await req.session.cart.push(doc)
    console.log(req.session.cart)

What happens is each time a product is added to the cart, it doesn't keep the existing data in there. So if I go to add two products, only the latest one shows in there. How can I fix this?


Solution

  • To explain your problem: the req.session.cart = [] code is emptying your req.session.cart data by passing it a value of empty array = [] every time your /addtocart endpoint is triggered.

    A solution would be:

    router.post('/addtocart', authCheck.login, async(req, res) => {
    
        // req.session.cart = []
        let updatedCart = []
        let { cart } = req.session
        
        let doc = {
         ...req.body
         }
        // await req.session.cart.push(doc) //await is unnecessary here
        updatedCart.push(...cart, doc)
        req.session.cart = updatedCart
        console.log("req.session.cart: ", req.session.cart)
    

    You can read more about the await keyword at MDN documentations - await.

    Let me know if you have any other question.