سؤال

I am having a problem with getting user profile data from within a template helper in Meteor 0.8.0. This code worked fine in the previous version, but since upgrading this morning it is broken. I originally thought this was a problem with the template helpers being run twice, but as I dig in I found the problem a little more nuanced than that.

Below the template helper 'findClientLiason' is called twice (it's output logged 2x in the console). The first time the user will show up as 'undefined' the second time the correct user object will come through the way I expect it to. Both times the 'clientLiason' will output correctly.

The most interesting thing to me is that if I remove the 'var user = Meteor.users.findOne({_id: clientLiason});' call to get the findOne call the helper is only called once.

It looks to me like the call to the Meteor.users collection forces another call to the database. And that the first time it calls it the Meteor.users collection is empty.

I have the publication and subscription shown below. I am using a the Iron Router global waitOn() function, but am wondering if the Meteor.users collection should be loaded earlier?

Any ideas would be appreciated. Thanks again.

publications.js

Meteor.publish('allUsers', function() {
    return Meteor.users.find();
});

router.js

Router.configure({
    layoutTemplate: 'layout',
    loadingTemplate: 'loading',
    waitOn: function() { 
        return [    
            Meteor.subscribe('clientsActive'),
            Meteor.subscribe('allUsers'),
            Meteor.subscribe('notifications')
        ];
}
});

clientItem.html

<template name="clientItem">
    {{findClientLiason clientLiason}}
</template>

clientItem.js

Template.clientItem.helpers({
    findClientLiason: function(clientLiason) {
        var user = Meteor.users.findOne({_id: clientLiason});
        console.log(clientLiason);
        console.log(user);
        return user.profile.name;
    }
});
هل كانت مفيدة؟

المحلول

This makes sense, because what's happening is that first the template is being rendered when the page loads and the users collection is empty, and then it's being re-rendered as the data changes (eg. the local mongo collection is filled).

You should write your templates to expect to start on page load with no data. I would change the helper to something like this:

findClientLiaison: function(clientLiaison) {
  var user = Meteor.users.findOne(clientLiaison);
  if (user) {
    return user.profile.name;
  }
  return "no data yet";
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top