I am trying to display some data from server in HBS but it doesn't work every time. Some times HBS will act as if there is no data being passed so I'm guessing it loads too fast before the object is rendered, how can I await for the req.user to reach front end before loading /profile?
The code below grabs req.user object from dbs and renders it to hbs:
router.get("/profile", authController.isLoggedIn, (req, res) => {
if (req.user) {
res.render("profile", { user: req.user});
}
HBS:
<div class="order-info-content">
{{#unless user.orders.[0].id}}
<h4>You do not have any recent orders</h4>
<br>
<a href="" id="account-info-edit">View our latest competitions!</a>
<br>
{{/unless}}
{{#if user.orders.[0].id}}
<div class="order-text">
<h4>{{user.orders.[0].date}}</h4>
<h4>ID: #{{user.orders.[0].id}}</h4>
<h4>Total: £{{user.orders.[0].total}}</h4>
</div>
<div class="order-images">
<img id="order-image" src="/Images/price 2.jpg" alt="">
</div>
{{/if}}
Edit: Back-end:
exports.isLoggedIn = async (req, res, next) => {
if (req.cookies.jwt) {
try {
const decoded = await promisify(jwt.verify)(
req.cookies.jwt,
process.env.JWT_SECRET
);
db.query(
"SELECT * FROM user WHERE id = ?",
[decoded.id],
(error, result) => {
if (!result) {
return next();
}
email = result[0].email;
req.user = result[0];
db.query("SELECT * FROM orders WHERE email = ?", [email],
(error, result) => {
if (result[0]) {
req.user["orders"] = result;
console.log(req.user.orders)
};
}
)
return next();
}
);
} catch (error) {
return next();
}
} else {
next();
}
};
This code will work 50% of the time, output will either be "You do not have any orders" OR the orders will show, the output is random between theses two option when I reload the page.