Reputation:
I have a collection which is published by the server, subscribed to by the client and a template helper displayed on the page. It all works great, but each time I refresh the page because the subscription depends on the userId of the user logged in it appears as if the code runs first before the browser knows the user is logged in (I assume?) and therefore returns an error.
My code:
// on the server
Meteor.publish('reputation', function() {
return Reputation.find({userId: this.userId});
});
// on the client
Reputation = new Mongo.Collection('reputation');
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound',
waitOn: function() {
return [Meteor.subscribe('reputation')];
}
});
Template for reputation:
<template name="reputation">
{{#if reputationCount}}
<li><a href="#"><span class="badge badge-inverse">{{reputationCount}}</span></a></li>
{{/if}}
</template>
and the helper:
Template.reputation.helpers({
reputationCount: function(){
return Reputation.findOne({userId: Meteor.userId()}).reputation;
}
});
The error I get on first refresh:
Exception in template helper: TypeError: Cannot read property 'reputation' of undefined...
It works after this, just annoying to have an error in the console. I thought by using the 'waitOn' function in the router then it wouldn't give the error, but I'm missing something obvious I think.
Upvotes: 0
Views: 341
Reputation: 938
Please try this helper code instead:
Template.reputation.helpers({
reputationCount: function(){
var rep = Reputation.findOne({userId: Meteor.userId()});
return rep && rep.reputation;
}
});
Here is a nice explanation of this behavior
Upvotes: 0