Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router 4.x - PrivateRoute not working after connecting to Redux

PrivateRoute available in Example https://reacttraining.com/react-router/web/example/auth-workflow is not working after connecting with Redux.

My PrivateRoute look almost same to the original version but only connected to Redux and used it instead of fakeAuth in the original example.

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

 PrivateRoute.propTypes = {
  auth: PropTypes.object.isRequired,
  component: PropTypes.func.isRequired
 }

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

export default connect(mapStateToProps)(PrivateRoute);

Usage and result:-

  1. NOT working but desired & expecting to work
    • <PrivateRoute path="/member" component={MemberPage} />
  2. working but NOT desired to used like this
    • <PrivateRoute path="/member" component={MemberPage} auth={auth} />
  3. working. JUST to work but NOT desired to used at all. An understanding from this point is that, if you connect original PrivateRoute to Redux you need to pass some additional props (any prop) to make PrivateRoute working otherwise it does not work. Anyone, please give some hint on this behavior. This is my main question
    • <PrivateRoute path="/member" component={MemberPage} anyprop={{a:1}} />
like image 390
Premchandra Singh Avatar asked May 10 '17 12:05

Premchandra Singh


People also ask

Does Redux work with react router?

You can use the connected-react-router library (formerly known as react-router-redux ). Their Github Repo details the steps for the integration. Once the setup is complete, you can now access the router state directly within Redux as well as dispatch actions to modify the router state within Redux actions.

Is react-router-Redux deprecated?

react-router-redux is deprecated. Use connected-react-router. by Gobinda Thakur | Medium. react-router-redux is deprecated.

Does react router reset state?

React-router resets all states of App component when I change route.


1 Answers

Complementary to @Tharaka answer you can pass {pure: false} to connect method as described in react-redux troubleshooting section.

React-redux makes shallow comparison of props in shouldComponentUpdate hook to avoid unnecessary re-renders. If context props changed (react-router) it doesn’t check for that and it assumes nothing has changed.

{ pure:false } simply disables this shallow comparison.

like image 55
Tomasz Mularczyk Avatar answered Sep 21 '22 19:09

Tomasz Mularczyk