Startup and Meteor.user race condition

Hi all,

I try to call a synchronize method if a user reconnects to my webapp, i.e. when he didn’t press logout button and later revisits the site. I tried to tackle this in the startup function as follows:

if (Meteor.isClient) {
    Meteor.startup(function () {
        if (Meteor.user() != null) {
            console.log('synchronizing now');
            Session.set('isSynchronizing', true);
            Meteor.call('synchronize', function(error, result){
              if (error) {
                alert(error);
              }
            });
        } else {
            console.log('not synchronizing');
        }
...

The problem is that sometimes Meteor.user() != null evaluates to true and sometimes to false. So, refreshing the page sometimes triggers the synchronization and sometimes not. I suspect a race condition going on.

Any ideas on how to deterministically call the synchronization method whenever a user revisits the application?

With kind regards,
Koen

!! Meteor.userId
!! Meteor.user()

but it should be consistent anyway. Do you have fast-render ?

I don’t have fast-render enabled yet. Should I?

if you want to have user login status available at startup, I would strongly suggest to add that package

I just installed the fast-render package, didn’t change any code (i.e. I didn’t add fastrendered: true to my ‘/’ route) but it seem to work already. Thanks!

I think you are trying to access Meteor.user() when the Meteor.users subscription is not ready (it is sometimes ready and sometimes not, depending on the startup sequence). On client, Meteor.startup will run when the DOM is ready, not when universal subscriptions are ready (see here).

Does using Meteor.userId() instead of Meteor.user() solve the problem?

Also, you might want to check this package. I’m not sure what it does exactly, but, well, it sounds close to your what you’re doing…