john doe
john doe

Reputation: 9660

Higher Order Components and Authenticate Routes

I am creating Higher Order Components in React and making sure that user cannot access the protected routes. Everything works fine but I am unsure where to put the code for checking the redux state. Currently, in the code below I have placed all the code in componentDidMount. This is because componentWillMount is deprecated. Is this the best place to check because componentDidMount is triggered after the component has been mounted.

import React, { Component } from 'react';
import { connect } from 'react-redux'

export default function(ComposedComponent) {

  class Authenticate extends Component {

    componentDidMount() {

      if(!this.props.isAuthenticated) {
        this.props.history.push('/')
      }

    }

    render() {
      return (
        <ComposedComponent {...this.props} />
      )
    }
  }

const mapStateToProps = (state) => {
  return {
    isAuthenticated: state.isAuthenticated
  }
}


return connect(mapStateToProps)(Authenticate)

}

Upvotes: 0

Views: 271

Answers (2)

Estus Flask
Estus Flask

Reputation: 222379

This is the purpose of React Router Redirect component:

render() {
  return !this.props.isAuthenticated ? (
    <Redirect to="/" />
  ) : (
    <ComposedComponent {...this.props} />
  )
}

Upvotes: 0

thedude
thedude

Reputation: 9812

Assuming the correct state is available at construction, you can do the redirect in the constructor:

class Authenticate extends Component {
   constructor(props) {
      super(props);
      if(!props.isAuthenticated) {
         props.history.push('/')
      }
   }
...
}

Upvotes: 0

Related Questions