1

I am using Firebase in my React project. The issue that the app would not redirect to Login page when users not logged in yet.

In my Home.js I have This page allows to only users who have already logged in the app.

class Home extends React.Component {
constructor(props) {
  super(props);
}

logout = () => {
  firebase.auth().signOut();

  this.props.history.push("/login");
};

render() {
  if (firebase.auth().currentUser === null) {
    return <Redirect to="/login" />;
  }

  return (
    <div>
      <div>
        <Button variant="contained" color="primary" onClick={this.logout}>
          Google Logoout
        </Button>
      </div>
    </div>
  );
}
}

export default withRouter(Home);

Actually, I use for classifying if the user is logged in or not by firebase.auth().currentUser.

Doug Stevenson
  • 268,359
  • 30
  • 341
  • 380
k10a
  • 773
  • 1
  • 7
  • 21

1 Answers1

5

A simple one. This can be done by using onAuthStateChanged from firebase like so:

firebase.auth().onAuthStateChanged(user => {
   user ? history.push("/dashboard") : history.push("/login");
   renderApp();
});

If there is a user, redirect him to in my case dashboard, if not, redirect him to login.