Created
November 17, 2017 12:54
-
-
Save alexbeletsky/c6366776b5f37f2204b3f079a975fe98 to your computer and use it in GitHub Desktop.
This file contains 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, { PropTypes } from 'react'; | |
import { connect } from 'react-redux'; | |
import { push } from 'react-router-redux'; | |
export default function requiresAuth(Component) { | |
class AuthenticatedComponent extends React.Component { | |
static propTypes = { | |
user: PropTypes.object, | |
dispatch: PropTypes.func.isRequired, | |
}; | |
componentDidMount() { | |
this._checkAndRedirect(); | |
} | |
componentDidUpdate() { | |
this._checkAndRedirect(); | |
} | |
_checkAndRedirect() { | |
const { dispatch } = this.props; | |
if (!this.props.user) { | |
dispatch(push('/signin')); | |
} | |
} | |
render() { | |
return ( | |
<div className="authenticated"> | |
{' '} | |
{this.props.user ? <Component {...this.props} /> : null}{' '} | |
</div> | |
); | |
} | |
} | |
const mapStateToProps = state => { | |
return { user: state.account.user }; | |
}; | |
return connect(mapStateToProps)(AuthenticatedComponent); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment