Search code examples
meteormeteor-accountsmeteor-helper

Getting a username from ID without autopublish


I just got done with the rough draft of my app, and thought it was time to remove autopublish and insecure mode. I started transfering all the stray update and insert methods I had been calling on the client to methods. But now I'm having trouble returning a username from an ID.

My function before: (that worked, until I removed autopublish)

challenger: function() {
  var postId = Session.get('activePost');
  var post = Posts.findOne(postId);
  if (post.challenger !== null) {
    var challenger = Meteor.users.findOne(post.challenger);
    return challenger.username;
  }
  return false;
}

Now what I'm trying:

Template.lobby.helpers({
  challenger: function() {
    var postId = Session.get('activePost');
    var post = Posts.findOne(postId);
    if (post.challenger !== null) {
      var userId = post.challenger;
      Meteor.call('getUsername', userId, function (err, result) {
        if (err) {
          console.log(err);
        }
        return result;
      });
    }
    return false;
  },

Using:

Meteor.methods({
    getUsername: function(userId) {
        var user = Meteor.users.findOne({_id: userId});
        var username = user.username;
        return username;
    },
    ...
})

I have tried blocking the code, returning values only once they're defined, and console.logging in the call-callback (which returned the correct username to console, but the view remained unchanged)

Hoping someone can find the obvious mistake I'm making, because I've tried for 3 hours now and I can't figure out why the value would be returned in console but not returned to the template.


Solution

  • Helpers need to run synchronously and should not have any side effects. Instead of calling a method to retrieve the user, you should ensure the user(s) you need for that route/template are published. For example your router could wait on subscriptions for both the active post and the post's challenger. Once the client has the necessary documents, you can revert to your original code.