CharlesRoger62 / ProjectPWS

0 stars 0 forks source link

Authentification basic #8

Open Mekouar-Ayoub opened 3 years ago

Mekouar-Ayoub commented 3 years ago

Pas de formulaire d'inscription juste tester connexion et connecter

Mekouar-Ayoub commented 3 years ago
  1. Higher-order Components (HOCs) Sometimes you have to ensure that a React component is only displayed when a user has logged into your application. Initially, you’ll do some sanity checks in your render method until you discover that you’re repeating yourself a lot. On your mission to DRY up that code, you’ll sooner or later find higher-order components that help you to extract and abstract certain concerns of a component. In terms of software development, higher-order components are a form of the decorator pattern. A higher-order component (HOC) is basically a function that receives a React component as parameter and returns another React component. Take a look at the following example:

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.