Cannot read property 'emails' of undefined

Hello.
I want to check if user email is verified:

var user = Meteor.user();
    if (!user.emails[0].verified) {
        // warning message
    }

But this code sometimes return in console:Cannot read property ‘emails’ of undefined
And sometimes not. The field in collection is exists and have a value.

What is the right way to retrieve status of email?

It means that Meteor.user() is returning undefined or null - no user is logged in.
http://docs.meteor.com/#/full/meteor_user

But user is logged in. I checkd it before :slight_smile:

I always ask myself if code I write is run sync/async.
And I think you dont need that user variable there at all.

It’s because the Meteor.users collection takes a bit to load, and so it depends on chance whether Meteor.user() will return the user or not (client-side).

Hints towards possible solutions: iron:router’s waitOn(), meteorhacks:fast-render with custom publication for current user record & subscription and injection into all routes, or rerunning checks reactively and just checking if the user is available yet or not, and doing nothing if it’s not, because on the next reactive rerun it will be available.

This is definitely something that bites lots of people initially. Quite unexpected.

1 Like

Meteor.user() is also a reactive source, so tracker will re-evaluate the code. So you should check if Meteor.user() returns != null.

2 Likes