2
votes

I have this template helper

Template.foo.helpers
  'bar':->
    console.log(Meteor.user().profile)
  'baz':->
    console.log(Meteor.user().profile)
  'buzz':->
    console.log(Meteor.user().profile)

And it logs the user object flawlessly.

But when I try to use it outside of the template helper it returns an Uncaught TypeError: Cannot read property 'profile' of undefined

Like this

checkProfile=(profile)->
  console.log profile

Template.foo.helpers
  'bar':checkProfile(Meteor.user().profile)
  'baz':checkProfile(Meteor.user().profile)
  'buzz':checkProfile(Meteor.user().profile)

I think that it executes the function before the Meteor.user() is loaded but when I try to log Meteor.userId inside the checkProfile, ex:

checkProfile=(profile)->
  console.log Meteor.userId()
  console.log profile

even

checkProfile=(profile)->
  console.log Meteor.userId()
  console.log(Meteor.user())

It logs the userId asap but still returns an uncaught error.

Now I concluded that Meteor.userId() is always available at the start of meteor and Meteor.user() object is loaded after?

Please literate me for this conclusion as these little things may become a big problem in my code in the future. Thanks.

Side Note:

I'm sure that the user is logged in because I'm testing error tests when the user is loggedIn. It's just when the page refreshes, the code runs and returns that error when it tries to run Meteor.user()

2

2 Answers

3
votes

Your error is caused by trying to access "profile" on undefined object. So it is not connected with checkProfile function.

Template's helpers are wrapped with Deps.autorun, it means that if you put reactive data source (like Meteor.user()) inside helper then helper will be rerun every time reactive data source is changed.

Consider using guards in your helper:

var user = Meteor.user();
var profile = user && user.profile;
if(profile){
  checkProfile(profile);
}

Above code will run few times - every time data from Meteor.user() is changed.

See how it works here : http://meteorpad.com/pad/j2bqKeMfuuLpbn2TW

Create account, open console and then refresh meteor app to see logs.

Side Note

You can check if you are logging in :

if(Meteor.loggingIn()){
  ...
}
0
votes

Are you calling checkProfile inside a publication by any chance? If so, you need to use publication's this.userId