Mostafiz Rahman
Mostafiz Rahman

Reputation: 8562

Meteor userId is present but user is undefined

While rendering my react component I'm getting Meteor.user() null. Then I tried accessing Meteor.userId() and got it correct as the logged in user's id. Also tried to access the user by Meteor.users.findOne() but didn't succeed.

My question is, why user object is being undefined though the userid is accessible?

I used following code snippet to test:

var uid = Meteor.userId();
console.log(uid);                                 // printed the _id correctly

var usr = Meteor.user();                
console.log(usr);                                 // undefined 

var usr1 = Meteor.users.findOne({_id: uid});
console.log(usr1);                                // undefined 

Upvotes: 3

Views: 790

Answers (2)

Xander
Xander

Reputation: 46

Meteor.user() is indeed not directly available, you can try the following:

Tracker.autorun(function(){
  var uid = Meteor.userId();
  console.log(uid);                                 // printed the _id       correctly

  var usr = Meteor.user();                
  console.log(usr);                                 // undefined 

  var usr1 = Meteor.users.findOne({_id: uid});
  console.log(usr1);  
});

This should first print undefined and after that print the correct user.

Upvotes: 2

Michel Floyd
Michel Floyd

Reputation: 20256

Meteor.userId() is available immediately on login. Meteor.user() requires the object be delivered via DDP to the client so it's not immediately available.

By default the profile key is published. Since you've turned off autopublish you may want to publish your own specific set of keys from the user.

I usually have:

server:

Meteor.publish('me',function(){
  if ( this.userId ) return Meteor.users.find(this.userId,{ fields: { key1: 1, key2: 1 ...}});
  this.ready();
});

client:

Meteor.subscribe('me');

You can also publish information about other users but there the list of keys to be shared is typically much smaller. For example you usually don't want to share the email addresses of other users with the logged-in user.

Upvotes: 3

Related Questions