Cedric Hadjian
Cedric Hadjian

Reputation: 914

splice() method works but array does not change after execution

I'm using express.js (node.js) to build an application. I have a products array declared as a session (req.session.products) in app.js folder. Here's the POST route:

router.post('/remove-cart', (req, res, next) => {

    var product_id = req.body.product_id; //get product id from client

    console.log(req.session.products)

    var n = req.session.products.indexOf(product_id); //get position of product id in the array
    req.session.products.splice(n, 1); //remove it

    console.log(req.session.products)

});

At the end of the route it logs this when n = 0:

[ '1', '3', '3', '3', '3' ]
[ '3', '3', '3', '3' ]

This is what I'm expecting, however, this does not affect the main session (req.session.products) and doesn't sort of "save" it. Why?

Upvotes: 2

Views: 435

Answers (1)

cнŝdk
cнŝdk

Reputation: 32145

Your real problem here is that you are not returning the req.session.products array to your app, you need to send it back in the response.

In the end of your .post() method write this line:

res.send(req.session.products);

Upvotes: 1

Related Questions