Reputation: 499
I have a small app that I'm prototyping (I'm very new at sails) that has a task in a list. Simple stuff. However, when I create a task and forward to the list after create, the task doesn't appear on my list. If I do a page refresh it does.
Here's the code snippets:
In Task->Create
List.findOne(req.session.List.id)
.exec(function foundTasks (err, list) {
Task.find({where: { list: list.id }, limit: 1, sort: 'priority desc'})
.exec(function getTaskPriority (err, task) {
if (err) {
console.log(err);
req.session.flash = {
err: err
}
}
list.tasks.add({name: req.param('name'), list: req.session.List.id});
list.save(function(err) {});
});
res.redirect('/list/show/'+req.session.List.id);
});
});
In List->Show
show: function(req, res, next) {
List.findOne(req.param('id'))
.populate('tasks')
.exec(function foundTasks (err, r) {
req.session.List = r;
if (err) return next(err);
res.view({
name: r.name,
tasks: r ? r.tasks : []
});
});
},
This doesn't happen when I create a normal item, only create an item through the .add() functionality. It happens in other places in my code as well (I have multiple contextual adds).
With this code, if I create task "Do this 1", I am redirected to my task list and "Do this 1" is not there. If I hit refresh, it does show. If I add "Do this 2", then I'm redirected to the task list and only "Do this 1" appears. Until I refresh, then "Do this 2" appears.
I thought perhaps there was an async issue (the page is loading faster than the record is being created and read in the db?) but I've added debug steps to factor that out.
Anyone have any ideas?
Upvotes: 0
Views: 347
Reputation: 1245
I think you are redirecting to the show page before saving the list. You have to do this:
list.tasks.add({name: req.param('name'), list: req.session.List.id});
list.save(function(err) {
res.redirect('/list/show/'+req.session.List.id);
});
Redirect to /list/show/:id
in the callback of list.save()
Upvotes: 2