Checking if user is logged in or not within a React component


#1
EntryLayout = React.createClass({
  render() {
    var layout;
    if (Meteor.user()) {
      layout = <MainLayout />;
    } else {
      layout = <WelcomeLayout />;
    }

    return (
      layout
    )
  }
});

I get this error message in the browser console:

Uncaught TypeError: Meteor.user is not a function(…)

Any suggestions?


Check if user is logged in with React + other React best practices
#2

Have you added the accounts-* packages? As far as I know, they are the ones responsible for creating the collections and functions related to Meteor.user


#3

I do the following, but I believe there is a better way.

You have to get the meteor data first, then check against it.
Here’s a component that displays the current user’s username

UserId = React.createClass({
	mixins: [ReactMeteorData],
	getMeteorData() {
	  return {
	    currentUser: Meteor.user()
	  };
  },

	render () {
		let renderContent;
		if(this.data.currentUser){
			renderContent = <span> User: {this.data.currentUser.username} </span>;
		}else{
			renderContent = <span> User was not defined </span>;
		}
		return  renderContent;
	}
});

#4

Meteor could possibly be not ready at render time? Also as @richenglish mentioned it won’t be reactive which is an issue too.


#5

You know what, I have not! I could have sworn these packages were added automatically by Meteor.


#6

This is definitely the correct way! We wanted to disentangle the Meteor data logic from render because this was more consistent with how people were using React outside of Meteor.


#7

Awesome guys, as always thank you for your help and insight. I’m going to test this out and report back for would-be googlers.