Nyxynyx
Nyxynyx

Reputation: 63619

Meteor.userId() undefined in Iron Router Route After Logging In

When a user first loads the site without logging in, then logs in, the route account defined below will resolve to /profile/null. The user must refresh the site before the route's path becomes correct.

this.route('account', {
    template: 'profile',
    path: '/profile/' + Meteor.userId()
})

The reason for creating a route specially to take the parameter Meteor.userId() is because I'm using a package that requires me to define the path name, ie: {{> ionTab title="Account" path="account"}} which I dont think can take a parameter.

Whats the better way to refine this route?

Upvotes: 1

Views: 427

Answers (1)

saimeunt
saimeunt

Reputation: 22696

Route definition happens once when your app is started, at this time Meteor.userId() is still undefined, so that's why your code is not working, but the whole approach is wrong, you should instead define your route as follow :

Router.route("/profile/:_id",{
  name:"profile",
  template:"profile",
  waitOn:function(){
    return Meteor.subscribe("userProfile",this.params._id);
  },
  data:function(){
    var user=Meteor.users.findOne(this.params._id);
    return {
      user:user
    };
  }
});

What you may have missed in the iron:router docs is the possibility to define routes taking a parameter (/path/:param syntax) and use this parameter to configure the route subscriptions and data context.

EDIT

If you want to get the corresponding dynamic path for this route, you can use the path method :

HTML

<template name="myTemplate">
  {{> ionTab title="Account" path=accountPath}}
</template>

JS

Template.myTemplate.helpers({
  accountPath:function(){
    return Router.path("profile",Meteor.user());
  }
});

Upvotes: 1

Related Questions