Knowing When There is *NOT* a Logged-In User?

I believe Meteor.userId is initially null, but is then filled in with the id of the currently logged-in user. If there is no logged-in user, it stays null.

The question is, how do I know if there is a logged-in user, vs. when the client is waiting to find out if there is a logged in user? I’d like my app to know asap.

The reason I ask is that I want to put up a sign-in screen if the user is not logged in. If there is a logged-in user, I’d like to avoid them seeing the sign-in screen while the client is waiting to find out that they are logged in. :slight_smile:

To put it another way: let’s say I had a “loading” message on screen, waiting to find out if there is a logged-in user. It so happens that in this case, there is no logged-in user. How would my app know that there is no logged-in user?

You need to use Meteor.loggingIn(). I use it like this on my react layouts

  const user = Meteor.user();
  const isLoggingIn = Meteor.loggingIn();

  if (!isLoggingIn && !user) {
    FlowRouter.go('login');
  } else if (!isLoggingIn && user) {
    // User is logged in
  }
4 Likes

I don’t know if it’s documented anywhere, but Meteor.user() returns undefined before the login checks run on startup. After that, it returns null if no user is logged in, or a user object if a user is logged in.

4 Likes

Thats interesting, never noticed it before.

It might be an issue on the future to rely on that, even more knowing that there might be a rewrite of those modules to TS. But not something to worry on the short term.

Awesome. Thanks very much!

Ahhh thanks. This works amazing with meteor-react-hooks. No need for loggingIn anymore.

1 Like