Tyler Jones
Tyler Jones

Reputation: 1333

Meteor user profile can only read after refresh

for user data, I have a publish/subscribe that looks like this:

Meteor.publish("allUserData", function () {
    return Meteor.users.find({}, {
            fields: { "emails": 1, "_id": 1, "profile": 1 }
        }
    );
});

Meteor.subscribe("allUserData");

But, when I try to read the profile, it's always undefined until I refresh the page, then I can read it. I'm trying to read the profile as follows:

Meteor.user().profile

What am I doing wrong? Why does it work when I refresh the page, but not on initial load? I've tried the property names in the publish function with and without quotes...

Upvotes: 1

Views: 689

Answers (1)

ram1
ram1

Reputation: 6470

Meteor.user().profile isn't available until a fraction of a second after Meteor.user() is. Also, when a user account is created it does not have a profile. The solution is to use a timeout in a reactive function.

Meteor.autorun(function(handle) {
  if (Meteor.user()) {
    if (Meteor.user().profile) {
      // use profile
      handle.stop()
    }
    else {
      setTimeout(function(){
        if (!Meteor.user().profile) {
          // new user - first time signing in
          Meteor.users.update(Meteor.userId(), {
            $set: {
              'profile.some_attribute': some_value
            }
          })
        }
      }, 2000)
    }
  }
})

Upvotes: 2

Related Questions