Technologies:
Tolerim
a month ago
How can I set a global variable in Express and then render it using Handlebars?
In my Handlebars code, I need to access user data that I have set globally in app.js. I have created a global variable using middleware that sets the value of "res.locals.user" to "req.user" or "null" if no user is logged in. My index.hbs file has code that correctly renders post titles and bodies for each post. However, I want to display an edit icon above the posts that were created by the logged-in user. If there are six posts on the page and only two were created by the logged-in user, there should only be update icons above those two posts. The updateIcon function will take three arguments: the userid of the post creator, the logged-in user, and the post id. I have implemented this function in hbs.js. When I attempt to view all posts, I encounter an error message that reads "Cannot read properties of undefined (reading 'id')" in reference to line 25, column 50 of my hbs.js file, where I attempt to access the "_id" property of a user.
Answers(2)
Vogi
a month ago
Verified Answer
It seems that you are trying to access the "_id" property of an undefined reference. You need to find out which of "req" or "user" is not defined and why. One solution is to change "User.findById(req.user._id)" to "User.findById(req.auth._id)".
If you are still having trouble, could you please share your code so I can help you better?
Sources
[Solved] Cannot read Properties of Undefined in JavaScriptResolving TypeError: Cannot Read Property of Undefined in JavaScriptTypeerror: cannot read property '_id' of undefined - CodeProjecthandlebars - cannot read property of undefined - Stack OverflowTypeError: Cannot read properties of undefined (reading '_id')Cannot read properties of undefined (reading 'id') - TrackJSTolerim
a month ago
The error message indicates that the postUser variable is undefined, and therefore does not have the _id property that is being attempted to be accessed in the updateIcon function.
To ensure that the postUser variable is defined and has the necessary properties, we can modify the updateIcon function to include a check for postUser before attempting to access its properties.
Here's an updated version of the updateIcon function:
updateIcon: function (postUser, loggedInUser, postId, floating = true) {
if (!postUser || !loggedInUser) {
return ''; // Return nothing if either argument is undefined
}
if (postUser._id.toString() === loggedInUser._id.toString()) {
if (floating) {
return `<a href="/posts/update/${postId}" class="btn-floating halfway-fab blue"><i class="fas fa-edit fa-small"></i></a>`;
} else {
return `<a href="/posts/update/${postId}"><i class="fas fa-edit"></i></a>`;
}
} else {
return '';
}
},
In this updated version, we first check if postUser or loggedInUser are undefined, and if so, we return an empty string. Otherwise, we proceed with the rest of the function as before. This should prevent the error from occurring.