Meteor takes time to know if there's a {{currentUser}} or not
Asked Answered
H

2

5

I've a few code that I want to run only when there's noUser and a few when there's a currentUser.
All these are inside the navigation template. Like so...

   {{#if currentUser}}  
     <li class="nav"><a href="{{pathFor 'create'}}">Post</a>  
     </li>  
     <li class="nav"><a>Ola, {{thisUser}}!</a>  
     </li>  
     <li class="nav"><a href="#" id="logout">Log Out</a>  
     </li>  
   {{/if}}  

   {{#if noUser}}  
      <li class="nav"><a href="{{pathFor 'signup'}}">Sign Up</a>  
      </li>  
      <li class="nav"><a href="{{pathFor 'login'}}">Login</a>  
      </li>  
   {{/if}}  

So the problem is that when there's a currentUser(i.e, I'm logged in) and I refresh the page, the code inside the {{#if noUser}} block shows up first then the {{#if currentUser}} block, while the {{#if noUser}} block was only meant to show up when there is no user.
Here's the helper code for the template..

Template.navigation.helpers({

    thisUser: function () {
            return Meteor.user().username;

    },

    noUser: function () {
        var user = Meteor.user();

        if (!user) {
            return true;
        };
    }


});

Don't know what am I doing wrong here. :(
Please help.

Heathcote answered 26/10, 2014 at 17:2 Comment(0)
L
10

You should use if else conditions instead of noUser helper. And to prevent showing "noUser" block while logging in you have to use {{ loggingIn }} helper. Something like this:

{{#if loggingIn}}
  <p>Loggin in...</p>
{{else}}
  {{#if currentUser}}  
    <li class="nav"><a href="{{pathFor 'create'}}">Post</a>  
    </li>  
    <li class="nav"><a>Ola, {{thisUser}}!</a>  
    </li>  
    <li class="nav"><a href="#" id="logout">Log Out</a>  
    </li>  
  {{else}}  
    <li class="nav"><a href="{{pathFor 'signup'}}">Sign Up</a>  
    </li>  
    <li class="nav"><a href="{{pathFor 'login'}}">Login</a>  
    </li>  
  {{/if}}
{{/if}}

Because Meteor does not know immediately whether user is logged in or not. Therefore you have to use loggingIn helper.

Lazar answered 26/10, 2014 at 18:21 Comment(0)
L
0

Why don't you refactor your code like this ?

{{#if currentUser}}  
  <li class="nav"><a href="{{pathFor 'create'}}">Post</a>  
  </li>  
  <li class="nav"><a>Ola, {{thisUser}}!</a>  
  </li>  
  <li class="nav"><a href="#" id="logout">Log Out</a>  
  </li>  
{{else}}  
  <li class="nav"><a href="{{pathFor 'signup'}}">Sign Up</a>  
  </li>  
  <li class="nav"><a href="{{pathFor 'login'}}">Login</a>  
  </li>  
{{/if}}

You might want to have a look to http://docs.meteor.com/#meteor_loggingin to show a loading indicator if needed.

Litigable answered 26/10, 2014 at 17:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.