Sato
Sato

Reputation: 8582

Meteor.user() is undefined when directly access the url

I have a url http://localhost:3000/test :

Template.test.onRendered(function() {
   console.log(Meteor.user());
});

If I first open http://localhost:3000/, then click the test link, Meteor.user() will be printed.

But if I directly open http://localhost:3000/test(Input the url in Chrome's address bar and hit enter), Meteor.user() is undefined.

Why??

Upvotes: 1

Views: 68

Answers (1)

saimeunt
saimeunt

Reputation: 22696

That's because Meteor logging in process is not instantaneous upon your app first load, it usually takes a few ms before the user actually gets connected, hence Meteor.user() returning undefined in your template onRendered lifecycle event.

I'm unsure what you're trying to achieve but you can solve this problem by introducing reactivity inside your onRendered handler :

Template.test.onRendered(function() {
  this.autorun(function(){
    console.log(Meteor.user());
  });
});

Declaring a reactive computation using Tracker.autorun will allow your code to rerun whenever the value of Meteor.user() is updated, and particularly on initial logging in resume process.

Upvotes: 1

Related Questions