How to use Tracker.autorun? Meteor.userId () undefined immediately after page refresh

I have a limited page using Meteor.userId () and roles:

class AdminPage extends Component {
render() {
 return (
  <div>
    {
      Roles.userIsInRole(Meteor.userId(), 'admin') ? (
        <Master_Layout renderCenter={<Article_Editor />}/>
      ) : browserHistory.push('/')
    }
  </div>
)
}
}

      

This code redirects the user to "/" after update because Meteor.userId () is undefined. How can I make sure Meteor.userId () is not undefined before rendering the page after refresh?

I've been looking for answers. I found Tracker.autorun as a solution, but I didn't figure out how to apply it.

Thanks for the help. I have updated the code:

constructor(props) {
super(props);

this.state = { user: '' };
}
componentDidMount() {
var $this = this;

Tracker.autorun(function () {
  let user = Meteor.user();
  if(user != undefined) {
    $this.setState({ user: user });
  }
});
}
render() {
if(Roles.userIsInRole(this.state.user, 'admin')) {
  return (
    <div>
      <Master_Layout renderCenter={<Article_Editor />} />
    </div>
  )
} else {
  return <div>loading...</div>
}
}
}

      

Observable required parts:
$ this = this;
user = Meteor.user (); // Meteor.userId () doesn't work.
removed the browserHistory because it will navigate to the user.

Now I just need to find a solution to determine the user / userId before setting the render.

0


source to share


1 answer


Tracker.autorun

allows you to automatically call a function whenever the reactive data source changes.

Simply put, it Tracker.autorun()

takes a function as input, runs that function now, and returns whenever the data source changes later.

In your case you can use Tracker.autorun()

to track user document as Meteor.user()

and Meteor.userId()

are reactive. The componentDidMount()

call Tracker.autorun()

and save the user the document in a different location, when it will change.



Hope the following piece of code helps:

componentDidMount() {
        var context = this;

        Tracker.autorun(function(){
            let user = Meteor.user();
            if (user != undefined) {
                context.setState({ user: user, });
            }
        });
    }

      

+1


source







All Articles