[closed] How to wait until ``Meteor.users`` is available on HOT page reload?


#1

Hi guys,

is there a way to wait until a collection is available until running the next line of code? Right now I am struggeling with Meteor.users not being available.

This is an easy code-example that shows how Meteor.users is NOT available. BUT when clicking the button it is available…

if (Meteor.isClient) {
  // Those lines have problems finding Meteor.users and Meteor.user()!
  console.log('AFTER A HOT PAGE RELOAD Meteor.user does IS NOT availabl');
  console.log('Meteor.user()');
  console.log(Meteor.user());  // NOT available: HOW do I wait with this call, UNTIL Meteor.users Collection is available?
  console.log('Meteor.userId()');
  console.log(Meteor.userId());
  console.log('Meteor.users.find().count()');
  console.log(Meteor.users.find().count());  // shows 0, although there are users

  Template.hello.events({
    'click button': function () {
      // everything works fine when pressing the button
      console.log('Meteor.user()');
      console.log(Meteor.user());
      console.log('Meteor.userId()');
      console.log(Meteor.userId());
      console.log('Meteor.users.find().count()');
      console.log(Meteor.users.find().count());
    }
  });
}

Any suggestions? :smiley:


#2

this discussion should help you


#3

What do you want to do with this data ?
With reactive programming in Meteor, everything start with a data change and ends with an output/display.


#4

I am using this with Flow-Router to secure an url. When the user does NOT have the right he is directed to home.

It works fine, but not on a page refresh…

doesCurrentUserHavePermission = function(permission) {
  // this give me problems: on a page-refresh Meteor.user() returns undefined
  // although the user is actually logged in and has the permission
  var currentUser = Meteor.users.findOne({ _id: Meteor.userId() });
  if (Roles.userIsInRole(currentUser, [permission]) ) {
    return true;
  }
  return false;
};

LoggedInRoute.group({
  triggersEnter: [
    function(context, redirect) {
      if (!doesCurrentUserHavePermission('permission')) {
        FlowRouter.go('home');
      }
    }
  ]
});

#5

I’m not familial with flow router, but the problem here is that the user data is not available yet when you make your request.


#6

Yeah you are totally right.

So basically we have not solved the original question, but I’ll close this topic as we solved my attached real useCase.

In Flow-Router is seems to be a bad idea to do auth-stuff on router-level, see here https://kadira.io/academy/meteor-routing-guide/content/implementing-auth-logic-and-permissions.

I got misslead by this howto here (https://medium.com/@satyavh/using-flow-router-for-authentication-ba7bb2644f42) - so be warned: don’t follow it and follow official FlowRouter tutorial instead. :slight_smile: I guess that template-level authorisation is the way to go!