user7075574
user7075574

Reputation:

How to use Redux inside a React Router stateless middleware?

When some user try to access any page of my application, a React Router middleware is called to check if the user is logged in. The problem is that to access the Redux store I need to use store.getState() and if I use store.listen(...) I receive an error ('component' doesn't exist).

const PrivateRoute = ({ component: Component, ...rest }) => { // Receive component and path
  return (
    <Route { ...rest } render={(props) => {
        return store.getState().login.token.status === 200
          ? <Component { ...props } />
          : <Redirect to="/login" />
       }}
    />
  )
}

// store.subscribe(PrivateRoute) // Error when some page is requested

export default PrivateRoute;

I know that to listen changes on this function I need to pass a component, but I think it's not possible because it's a middleware. Do I really need to listen for changes in this case, if yes, how can I do this (how to mock this type of thing) ?

Obs : Example <PrivateRoute path="/private" component={() => <h1>Private</h1>}/>

Upvotes: 0

Views: 177

Answers (3)

Ram
Ram

Reputation: 432

After login have you dispatch an action to store the the login values in store. if yes check that.

and i think you can store the login token in localStorage read about WebStorage and easily get it back using store.get('keyname').

Upvotes: 0

Asif vora
Asif vora

Reputation: 3359

Using Redux

import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

const PrivateRoute = ({ component: Component, auth: auth, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      auth.isAuthenticated === true ? (
        <Component {...props} />
      ) : (
        <Redirect to="/login" />
      )
    }
  />
);

PrivateRoute.propTypes = {
  auth: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  auth: state.auth
});

export default connect(mapStateToProps)(PrivateRoute);

Upvotes: 0

Thakur Karthik
Thakur Karthik

Reputation: 3528

Try this.

const PrivateRoute = ({ component: Component, hasLogin, ...rest }) => (
 <Route
  {...rest}
  render={props => (
    hasLogin ? (
      <Component {...props} />
    ) : (
      <Redirect
        to={{
          pathname: '/login'
        }}
      />
    )
  )}
/>
)
export default connect(state => ({
 hasLogin: state.login.hasLogin
}))(PrivateRoute)

In the switch call like this

<PrivateRoute exact path='/' component={some page} />

Upvotes: 2

Related Questions