Reputation: 3592
I need to execute this piece of code
Template.addPost.onRendered ->
@$('#name').val(Meteor.user().profile.name)
But it seems that the template is rendered earlier than Users collection
gets populated on the Client. Thus returning me
Cannot read property 'profile' of undefined
How do I tackle this?
Upvotes: 1
Views: 468
Reputation: 64312
You can wait for the user to be loaded via an autorun:
Template.addPost.onRendered ->
@autorun (c) ->
# extract the name in a safe way
{name} = Meteor.user()?.profile
# once a name has been found, update the DOM and stop the autorun
if name
# note that name is an id so we don't need @$
$('#name').val name
c.stop()
We are also taking advantage of coffeescript's existential operator to safely extract the name value. In javascript this solution would look something like this:
Template.addPost.onRendered(function() {
this.autorun(function(c) {
var user = Meteor.user()
var name = user && user.profile && user.profile.name;
if (name) {
$('#name').val(name);
c.stop();
}
});
});
Upvotes: 2