Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor.user().profile returns 'profile' undefined

I have a helper called 'isActive' and a template named 'create'.. see below

Template.create.isActive = function () {
  return Meteor.user().profile.isActive;
};

When I try to run this code it returns the following in console: "Exception in template helper: TypeError: Cannot read property 'profile' of undefined".

Basically I want to pull the 'isActive' info from the current user profile and return it to the template. Any idea why this does not work?

Update

//startup on server side:
Meteor.publish("userData", function() {
  if (this.userId) {
    return Meteor.users.find({_id: this.userId},
      {fields: {'profile.isActive': 1}});
  } else {
    this.ready();
  }
});

//startup on client side
Meteor.subscribe('userData');

//router
this.route('list', {
  path: 'list',
  waitOn : function () {
    return Meteor.subscribe('userData');
  },
  data : function () {
    return Meteor.users.findOne({_id: this.params._id});
  },
  action : function () {
    if (this.ready()) {
      this.render();
    }
  }
});
like image 314
Jason Chung Avatar asked Aug 27 '14 16:08

Jason Chung


1 Answers

Meteor.user() is undefined. You are either not logged in with any user or your template is rendered before the users collection is synced to the client. If you use a router like iron router you can wait for the collection being available or for the user being logged on.

Without using a router the easiest would be to check if the user is defined:

Template.create.isActive = function () {
    return Meteor.user() && Meteor.user().profile.isActive;
}

Since Meteor.user() is reactive the template will be rerendered when the user changes, i.e. when it is available.

This is a common error btw, see also:

  • Meteor.user() Error: Uncaught TypeError: Cannot read property 'name' of null
  • How can I prevent Meteor.user()'s timing hole?
like image 82
Florian Avatar answered Oct 04 '22 14:10

Florian