Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'profile' of undefined in meteor.JS function?

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.

like image 970
troytc Avatar asked Jan 01 '13 00:01

troytc


1 Answers

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.

like image 147
Rahul Avatar answered Oct 24 '22 18:10

Rahul