简体   繁体   中英

Meteor.user().profile only defined after a page refresh

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".

I solve this by using iron-router to wait for profile to load:

//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('create', {
  path: 'create',
  waitOn : function () {
    return Meteor.subscribe('userData');
  },
  data : function () {
    return Meteor.users.findOne({_id: this.params._id});
  },
  action : function () {
    if (this.ready()) {
      this.render();
    }
  }
});

BUT... it only works when I refresh the page and not on initial load. Anybody know why this is happening? And have a fix or a better way to do this?

To avoid the error "Exception in template helper: TypeError: Cannot read property 'profile' of undefined" you need to check that Meteor.user() has returned an object. The standard pattern is:

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

Once your helper throws an error, reactivity will not work so you need to make sure to handle the case where the subscription data has not arrived yet.

Also, waiting on the 'userData' subscription will delay the template loading but the user profile is published automatically on login ( as a null subscription ). So your wait is causing an arbitrary delay which would increase the chance that Meteor.user() will be defined but it is not directly waiting on the data you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM