reselect

reselect (https://github.com/reduxjs/reselect) is an external library for Redux that helps to build selectors. The library has become de-facto standards for creating selectors in the frontend echo-system. 

In our application, one of the use cases where we need to use a selector is to store login information about the user. If a user signs in using credentials, we create a session for the user for a certain interval. This is very basics of authentication and authorization mechanisms. Let's say, if a user has entered the credentials correctly, then we save a isLoggedIn flag in store to indicate the user is logged in. Every time a user opens our application, we try to check for these props, and if it is true, we redirect the user to some dashboard page, otherwise, we redirect to the login page. Now, we can create a selector to get these props inside the login container, as follows:

export const mapStateToProps = createStructuredSelector({
  isLoggedIn: makeSelectLogedIn(),
});

The preceding snippet is created as follows:

  1. We are using createStructuredSelector from the reselect library. 
  2. We provide the mapStateToProps function as an argument to the connect function of Redux. This provides isLoggedIn props to the login component. 
  3. Inside the Login component, we can use React life cycle methods to check and redirect, as follows:
componentDidMount() {
    if (this.props.isLoggedIn) {
      this.props.history.push('/dashboard');
    } else {
this.props.history.push('/login');
} }

We will consume this code for creating login and logout functionality in the next chapter. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset