Skip to content

Instantly share code, notes, and snippets.

@johndavedecano
Created July 19, 2017 14:07
Show Gist options
  • Save johndavedecano/3d2f60007e122ddef11b27ffe4adac94 to your computer and use it in GitHub Desktop.
Save johndavedecano/3d2f60007e122ddef11b27ffe4adac94 to your computer and use it in GitHub Desktop.
ReactJS Redux Authentication HOC
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