Leoj Pyzynski
Leoj Pyzynski

Reputation: 231

Meteor never see's me as looged in

I want to detect if a logged in user has no records in the collection and then start them with some default values. So I use this at the beginning of my isClient part;

if (Meteor.isClient) {

  if(Meteor.user()){
    Meteor.subscribe('collection');
    var currentUserId = Meteor.userId();
    if (collection.find({"userID": currentUserId}).count() == 0)
    {       
      Meteor.call('initUser', currentUserId);
    }
  } else {
    console.log("You are not logged in");
  }
}

Problem is that it never see's me as logged in. Do I need to be calling this from a template or something? In the tutorial that I did they just had it all by itself.

Upvotes: 1

Views: 29

Answers (1)

saimeunt
saimeunt

Reputation: 22696

Your code looks good to me but it does not live in a reactive computation, meaning that it's going to run only once at the beginning of your code and never again, just like regular sequential programming.

You need to surround your code with a Tracker.autorun like this :

if (Meteor.isClient) {
  Tracker.autorun(function(){
    // Meteor.userId() is a reactive data source that will trigger invalidation
    // of the reactive computation whenever it is modified (on login/logout)
    var currentUserId = Meteor.userId();
    if(currentUserId){
      Meteor.subscribe('collection',function(){
        if (collection.find({
          userID: currentUserId
        }).count() === 0){       
          Meteor.call('initUser', currentUserId);
        }
      });
    } else {
      console.log("You are not logged in");
    }
  }
}

I've refactored it to only use Meteor.userId() because you don't use the currentUser properties in this piece of code.

Upvotes: 1

Related Questions