I'm trying to create divs using an object I pass with res.render(). However, sometimes the divs are created and sometimes they are not (if I refresh the page). I also use Bootstrap.
js/express:
router.get('/', checkSignIn, function(req, res, next) {
db = new sqlite3.Database(file);
var tasks = {};
db.serialize(function () {
var query = "SELECT tasks.id, tasks.name, tasks.status FROM tasks JOIN users ON users.privilege = tasks.privilege WHERE users.id = '" + req.session.userid + "'";
db.all(query, function (err, rows) {
for(i = 0; i < rows.length; i++) {
tasks[i] = {
name: rows[i].name,
status: rows[i].status
};
console.log(tasks[i]);
}
});
});
db.close();
res.render('index', {
title: 'Home',
css: ['style.css', 'dist/wu-icons-style.css'],
username: req.session.username,
tasks: tasks
});
});
hbs:
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="panel-group">
{{#each tasks}}
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">{{name}}</h3></div>
<div class="panel-body">{{status}}</div>
</div>
{{/each}}
</div>
</div>
</div>
</div>
The tasks object is properly populated every time, according to the console.log() that I've added. So I think the problem lies in Handlebars.
I kind of found a solution here: Handlebars not print {{this}} in each helper, but I don't use this. I tried ./name and ./status, but it didn't help. Can someone help me out here?
Your issue is async javascript, not handlebars. Your tasks object is populating, but you're rendering the html prior to that. If you console.log(tasks) right after the current position of db.close(), it will be an empty object. You need to move the render function inside the database call:
router.get('/', checkSignIn, function(req, res, next) {
db = new sqlite3.Database(file);
db.serialize(function () {
var query = "SELECT tasks.id, tasks.name, tasks.status FROM tasks JOIN users ON users.privilege = tasks.privilege WHERE users.id = '" + req.session.userid + "'";
db.all(query, function (err, rows) {
var tasks = {};
for(i = 0; i < rows.length; i++) {
tasks[i] = {
name: rows[i].name,
status: rows[i].status
};
console.log(tasks[i]);
}
res.render('index', {
title: 'Home',
css: ['style.css', 'dist/wu-icons-style.css'],
username: req.session.username,
tasks: tasks
});
});
});
db.close();
});