Trying to grok Express here. I'm using the express-session module and I've had no trouble when I'm using session variables that are objects or strings. However, I just can't seem to get arrays to work. I'm using the shopping cart technique as a lab rat. Here's the code that's causing me problems:
router.post('/', function(req, res) {
if (req.body.action == 'Add to Cart') {
var cart = req.session.cart = [];
cart.push(req.body.itemId);
res.redirect('/');
}
});
router.get('/', function(req, res) {
if (req.session.cart) {
var itemsInCart = req.session.cart.length;
}
res.render('index', {
title: 'Shopping Spree',
itemsInCart: itemsInCart,
products: [
{id: 1, item: 'Boeing 747', price: 4500},
{id: 2, item: 'Luxury Yacht', price: 200},
{id: 3, item: 'Mercedes AMG GT', price: 15000},
{id: 4, item: 'Apple iPhone 6', price: 2400},
{id: 5, item: 'Moet Hennessey', price: 5000}
]
});
});
And in the view: index.jade:
extends layout
block content
h2= title
p Cart(#{itemsInCart} items)
a(href="/cart") [VIEW CART]
table
thead
tr
th Item
th Price
tr
tbody
- for (var i in products) {
tr
td= products[i].item
td= products[i].price
td
form(action="/", method="post")
input(type="hidden", name="itemId" value="#{products[i].id}")
input(type="submit", name="action", value="Add to Cart")
- }
The first time the 'Add to Cart' button is clicked, itemsInCart is indeed updated to 1. Subsequent 'Add to Cart' clicks won't update that value.
Please advise.
Using this line
var cart = req.session.cart = [];
each time you call it, you redefine content of req.session.cart to [].
Try instead:
var cart = req.session.cart || [];
It will keep existing value of cart and you will not loose previous items
UPDATE
As for updated question, here is what you can do, to keep Jade's bindings updated:
var pageScope;
router.post('/', function (req, res) {
if (req.body.action == 'Add to Cart') {
var cart = req.session.cart = [];
cart.push(req.body.itemId);
pageScope.itemsInCart = req.session.cart && req.session.cart;
res.redirect('/');
}
});
router.get('/', function (req, res) {
pageScope.itemsInCart = req.session.cart && req.session.cart;
res.render('index', pageScope = {
//...
});
});
Idea is to update itemsInCart, every time, you increase the length of cart array.
Well, after many, many iterations, I finally got it to work:
router.get('/', function(req, res) {
if (req.session.cart) {
var itemsInCart = req.session.cart.length;
} else {
req.session.cart = [];
}
res.render('index', {
title: 'Shopping Spree',
itemsInCart: itemsInCart,
//...
});
});
then
router.post('/', function(req, res) {
if (req.body.action == 'Add to Cart') {
req.session.cart.push(req.body.itemId);
res.redirect('/');
}
});
I just don't know why I hadn't thought of this earlier. Must be one of my bad days.