Search code examples
meteormeteor-blazeflow-router

Access meteor.user subscription in template helpers using flow router


In my meteor app with Flow router, I am using the meteor subscription for fetching user data, but data in the helpers are not updating according to the user collection updations.

In my publications code,

Meteor.publish('fetchUserData', function(usrnm) {
 return Meteor.users.find({'username':usrnm}, {
 fields: {
  profile: true,
  services: true,
  emails: true,
  votedPatents: true,
  userType: true,
  followingUsers: true,
  followedByUsers: true
  }
 });
});

In my router.js file,

Subs =  new SubsManager();
FlowRouter.route('/:username', {
 subscriptions: function(params) {
  this.register('fetchUserData', Meteor.subscribe('fetchUserData', params.username));
},
 action: function(params) {
    BlazeLayout.render('main', {center: 'profile'});
  })      
 }
});

In my client code

Template.profile.onCreated(function() {
  this.autorun(function() {
    var handle = Subs.subscribe('fetchUserData', username);
  })
})


Template.profile.helpers({
  connections: function(){
    var u = Meteor.users.findOne({'username':username});
    return u;
  }
})

Also should note that the helper function returns undefined for users other than Meteor.user() and I had also tried How to access FlowRouter subscriptions in Meteor template helpers? , but the result is same


Solution

  • Your publication returns 1 user: the user with the username passed as a param, so on the client, when you subscribe to this publication, you get one user. When you do

    Meteor.users.find({....});

    you're searching through a collection that only has the one user you published.

    To fix this, you need:

    • to publish all users to the client (not ideal for security reasons, unless you take good care of filtering out users that the signed in user is allowed to see)

    or

    • subscribe to the publication with the user to look up each time you need to do a lookup (run the subscribe, then findOne() -> inefficient)

    or

    • use a Method that will return the user you need without exposing everyone.