How to check if user is authenticated before rendering page?

Viewed 1610

I'm using Next.js with redux and firebase auth.

What I'm trying to achieve is to check whether a user is logged in before being able to access some private pages.

I have created a component called AdminLayout which is wrapped around every private page. I get the currentUser as props using mapStateToProps but I'm not getting the value in the first run.

// admin-layout.component.jsx
// Imports

class AdminLayout extends React.Component {
  componentDidMount() {
    console.log(this.props.currentUser);
    // if (this.props.currentUser) {
    //   if (this.props.currentUser.currentUser.role != "admin") {
    //     Router.push("/admin/login");
    //   }
    // }
    // if (!this.props.currentUser) {
    //   Router.push("/admin/login");
    // }
  }

  render() {
    return (
      <React.Fragment>
            // Irrelevant code here
            {this.props.children}
            // Irrelevant code here
      </React.Fragment>
    );
  }
}

const mapStateToProps = (state) => ({
  currentUser: state.user.currentUser,
});

export default connect(mapStateToProps)(AdminLayout);

Any way to overcome this situation and allow only authenticated users to access the private pages?

0 Answers
Related