torayeff
torayeff

Reputation: 9702

Displaying Meteor.user()

I have this template:

<template name="index">
  {{#if currentUser}
    {{userid}}
  {{/if}}
</template>

What is the difference between

Template.index.helpers({
    userid: function() {
        return Meteor.user()._id;
    }
});

AND

Template.index.helpers({
    userid: Meteor.user()._id
});

The last one gives this error: Uncaught TypeError: Cannot read property '_id' of undefined

Upvotes: 0

Views: 58

Answers (1)

Tarang
Tarang

Reputation: 75945

The easiest thing to do is use {{currentUser._id}}

Meteor.user()._id is correct. The problem is when you load the page, initially the data is not available and Meteor.user() will be null until a DDP connection is established and your browser logs you in (this takes a few hundred milliseconds). Meteor.user() && Meteor.user()._id to correct this.

The difference between the two Meteor.user()._id is in one you are passing the first static value that loads when the template is loaded. It will stick to being that even if Meteor.user() changes, or you log out.

When you pass a function you tell the helper it can be recalculated and it will update if there are any reactive changed.

Upvotes: 2

Related Questions