I have the following code:
Template.analyze.userFullName = function() {
var u = Meteor.users.findOne({_id: this.userId}, {fields: {name: 1}});
return u.profile.name;
};
Meteor.users.findOne({_id: this.userId}, {fields: {name: 1}})
returns the following when used in the console:
Object
_id: "79ef0e67-6611-4747-b669-45cc163cc1d8"
profile: Object
name: "My Name"
But when I use it in code above I get this: Uncaught TypeError: Cannot read property 'profile' of undefined
Why is this happening? All I want to do is retrieve the user's full name in their profile and pass it to a template part.
The Template is being rendered immediately on pageload when the user is not available yet, which is causing an error. Thankfully since you're using the Users collection, which is reactive, you can just have it re-render when it becomes available. You do this by checking first if the object is not null:
Template.analyze.userFullName = function() {
// use Meteor.user() since it's available
if (Meteor.user())
return Meteor.user().profile.name;
};
This way, when the user is null (during load) the Template won't throw an error. Immediately upon the data being available, the reactivity will invoke the template again, and it will render on the screen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With