Josh
Josh

Reputation: 13

Bookshelf.js - After updating record, initial page load/query displays old record. After refresh data displays correctly

When I set a column to null using bookshelf, and redirect to the page which displays that data, the data displays the un-updated record, until I refresh. Here's the code:

        Table.where({id: req.param.id}).fetch()
        .catch(function (err) {
            console.log(err);
        })
        .then(function (results) {
            results.set('other_column', null);
            results.save();
            results.refresh();
            // Redirect to orders page
            res.redirect('/landing-page');
        });

The landing page query is this:

        Table.where({id: req.param.id}).fetch()
        .catch(function (err) {
            console.log(err);
        })
        .then(function (results) {
            data.results = results.attributes;
            res.render('display-page', data);
        });

Does anyone know how I can fetch the updated record, or let me know if I am updating a record incorrectly? Any help solving this issue would be much appreciated as I can't render a page with the old data after having user just updated it...

Upvotes: 1

Views: 242

Answers (1)

flaviodesousa
flaviodesousa

Reputation: 7815

You are writing you saving data like synchronous code, so the save() may (and often will) happen AFTER the refresh(). Try changing that to:

    Table.where({id: req.param.id}).fetch()
    .catch(function (err) {
        console.log(err);
    })
    .then(function (results) {
        return results
          .set('other_column', null)
          .save();
    })
    .then(function (results) {  // results should now include the saved data
        // Redirect to orders page
        res.redirect('/landing-page');
    });

Upvotes: 1

Related Questions