Open Mekouar-Ayoub opened 3 years ago
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { push } from 'react-router-redux';
export default function requiresAuth(WrappedComponent) { class AuthenticatedComponent extends Component { static propTypes = { user: PropTypes.object, dispatch: PropTypes.func.isRequired };
componentDidMount() {
this._checkAndRedirect();
}
componentDidUpdate() {
this._checkAndRedirect();
}
_checkAndRedirect() {
const { dispatch, user } = this.props;
if (!user) {
dispatch(push('/signin'));
}
}
render() {
return (
<div className="authenticated">
{ this.props.user ? <WrappedComponent {...this.props} /> : null }
</div>
);
}
}
const wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component';
AuthenticatedComponent.displayName = Authenticated(${wrappedComponentName})
;
const mapStateToProps = (state) => { return { user: state.account.user }; };
return connect(mapStateToProps)(AuthenticatedComponent); } The requiresAuth function receives a component (WrappedComponent) as a parameter, which will be decorated with the desired functionality. Inside that function, the AuthenticatedComponent class renders that component and adds the functionality to check if a user is present, otherwise redirecting to the sign-in page. Finally, this component is connected to a Redux store and returned. Redux is helpful, in this example, but not absolutely necessary.
ProTip: It’s nice to set the displayName of the component to something like functionality(originalcomponentName) so that, when you have a lot of decorated components, you can easily distinguish between them in the debugger.
Pas de formulaire d'inscription juste tester connexion et connecter