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:-
<PrivateRoute path="/member" component={MemberPage} />
<PrivateRoute path="/member" component={MemberPage} auth={auth} />
<PrivateRoute path="/member" component={MemberPage} anyprop={{a:1}} />
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.
react-router-redux is deprecated. Use connected-react-router. by Gobinda Thakur | Medium. react-router-redux is deprecated.
React-router resets all states of App component when I change route.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With