简体   繁体   中英

Ensure Meteor.user() is available on client after login

I found this weird issue and it looks quiet pathogenic!

I though Meteor.user() would always be available after you login, but I am seeing it to be not reliable at all as it often returns undefined.

After referring some SO questions, it seems that Meteor.user() may not be loaded fully due to "timing issues".

I need a reliable way to make sure that Meteor.user() is loaded fully at the client. Most of my code is using this approach to get user profile. So it would be great to be able to make this approach work rather than using approach given here

Meteor.user() will always be fully loaded at the client after login after some time . Not a very long time depending on the size of the user object itself, latency, and bandwidth, typically 1ms to 100ms. There's nothing you need to do to ensure it loads - you just need to account for the delay by waiting until it is loaded to run code that depends on it. For example you can use Tracker.autorun() to make something run as soon as Meteor.user() becomes available:

on the client:

Tracker.autorun(() => {
  if (Meteor.user()) {
    ... do the thing that depends on Meteor.user()
  }
});

In a helper or some other rendering code you typically want to code defensively, for example:

const username = Meteor.user() && Meteor.user().username;

will never break. It will just return undefined when there is no logged-in user or when the user object isn't yet available.

wrt your follow up question, as far as template helpers are concerned, a typical pattern is to render a spinner/loading animation template until the data for the template is ready then switch to the real template(s) when it is. That way your template code doesn't have to deal with not ready data. Here's a good tutorial on the subject .

As mentioned by @michel-floyd you can use Tracker.autorun(() => {/*..*/}); . Using global helper might be a better option though.

But according to your specific question:

I need a reliable way to make sure that Meteor.user() is loaded fully at the client.

Using Accounts.onLogin will be more efficient:

import { Accounts } from 'meteor/accounts-base';

Accounts.onLogin(() => {
  // User is logged in and its data fully loaded
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM