Search code examples
meteoriron-router

Why Meteor.user and Meteor.userId differ?


I have an interceptor:

Router.onBeforeAction(function() {
    if (!Meteor.userId()) {
        console.log("lets login");
        Router.go("login");
    } else {
        this.next();
    }
}, {
    except: ['login', 'signup']
});

It works very well, until I replace the !Meteor.userId() for Meteor.user(). It seems that .user when refreshing the page goes undefined and redirect it to my login page. My login router also verifies .user and here it is right.

Why this difference?


Solution

  • That's true, Meteor.userId() returns the id while Meteor.user() returns the object.

    However, returning an object (Meteor.user()) takes more time than just returning an ID, due to the asynchronous issue, by the time the script is checking if (!Meteor.user()) {...}, Meteor.user() has not been processed and returned yet!

    As a result, there are several ways to due with that asynchronous issue (for example, in Meteor/React application, we may have something like subscribe, and wait until the handle is ready)