Reputation: 10252
How can I get the userId
in Meteor.startup
function any ideas? I need it to run a loop that pings every 10 seconds but all I get is Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.
My code:
Meteor.startup(function() {
console.log(Meteor.userId());
});
Upvotes: 1
Views: 1996
Reputation: 75945
You're not likely to get the Meteor.userId()
in the startup
function because the data from subscriptions (such as who is logged in) will take a short while to arrive, by which time startup would have completed.
Use Tracker.autorun()
instead:
Tracker.autorun(function() {
if(Meteor.userId()) {
///
}
});
Be careful this will run whever the user logs in as well. To ensure it only runs once you could use a Session
that could store how many times its run, and stop it if it runs more than once.
Upvotes: 1
Reputation: 18068
The answer is clearly mentioned in the error message. By the way, you need to check whether logged in or not before trying to print.
Meteor.startup(function() {
if (this.userId)
console.log(this.userId);
});
Upvotes: 0