Created
July 19, 2017 14:07
-
-
Save johndavedecano/3d2f60007e122ddef11b27ffe4adac94 to your computer and use it in GitHub Desktop.
ReactJS Redux Authentication HOC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { connect } from 'react-redux'; | |
export default function requireAuth(WrappedComponent) { | |
class AuthenticatedComponent extends React.Component { | |
componentDidMount() { | |
this.checkAuth(this.props.isLoggedIn); | |
} | |
checkAuth(isLoggedIn) { | |
if (isLoggedIn) { | |
this.props.history.replace( | |
`/auth/login?next=${this.props.location.pathname}` | |
); | |
} | |
} | |
render() { | |
return this.props.isLoggedIn | |
? <WrappedComponent {...this.props} /> | |
: null; | |
} | |
} | |
const mapStateToProps = state => ({ | |
isLoggedIn: state.auth.get('isLoggedIn') && state.auth.get('user') | |
}); | |
return connect(mapStateToProps)(AuthenticatedComponent); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment