Calculate Age Error Help (SOLVED)

I’m trying to calculate a players age based on their birthdate stored in my database. I have the following code that seems to be working when i render the template but I’m getting this error in my console:

TypeError: Cannot read property 'dateOfBirth' of undefined.

Can anyone make a recommendation on why this is happening? Any help is much appreciated. Thank you in advance.

Template.showPlayer.helpers({

player: function () {
  return players.findOne(FlowRouter.getParam("_id"));
},

calculateAge: function() {
  var p = players.findOne(FlowRouter.getParam("_id"));
  var dob = moment(p.dateOfBirth).format('YYYYMMDD');

   return moment().diff(moment(dob, 'YYYYMMDD'), 'years')
}

});//end Template helper`

Your database is flapping, and the template is rendering before data has reached the client. You simply need to use defensive programming, and specify how to render the template if no data is available. Try this:

Template.showPlayer.helpers({

player: function () {
  return players.findOne(FlowRouter.getParam("_id"));
},

calculateAge: function() {
  var p = players.findOne(FlowRouter.getParam("_id"));
  if(p){
    var dob = moment(p.dateOfBirth).format('YYYYMMDD');
    return moment().diff(moment(dob, 'YYYYMMDD'), 'years')
  } else {
    return "----/--/--";
  }
}

});//end Template helper`

hmm… I’m not quite sure i understand why that worked, but it definitely did the trick. Thank you so much.

No problem.

Think of the templates as spinning, like a fan or car-engine. They begin rendering over-and-over as soon as the Meteor.startup() function is called. They can be rendering before data has reached the client, much like a car engine can idle in neutral before a gear is selected. When the subscription finally gets data from the publication, Blaze has data it can start using to render things with; much like the idling car engine can begin moving forward once it’s shifted into gear.

The defensive programming technique used above tells Blaze what to do when the engine is idling. The code you posted with was only telling Blaze what to do when it was in gear and moving forward.

Thanks for the great explanation. Much better understanding now. :smile: