Reputation: 179
I am designing react application with node server. I have created a custom Private Route
import React from 'react';
import {connect} from 'react-redux';
import {Route, Redirect} from 'react-router-dom';
class PrivateRoute extends React.Component{
render() {
const { isAuthenticated, component: Component, ...rest } = this.props;
return (
<Route {...rest} component={(props) => {
if(isAuthenticated){
return <Component {...props}/>
}
else{
return <Redirect to="/login" />
}
}}/>
)
}
}
const mapStateToProps = (state) => {
return{
isAuthenticated: state.auth.email !== '' ? true : false
}
}
const ConnectedPrivateRoute = connect(mapStateToProps)(PrivateRoute)
export default ConnectedPrivateRoute;
I am redirecting myself to dashboard route from node serer after login.
import React from 'react';
import axios from 'axios';
import {connect} from 'react-redux';
import { setAuthenticatedUser } from '../actions/authA';
class Dashboard extends React.Component{
constructor(props) {
super(props);
axios.get('/cookie').then((user) => {
if(user.data.email)
this.props.dispatch(setAuthenticatedUser(user.data));
})
.catch((e) => {
console.log("Got some error");
})
}
render() {
return (
<div>Dashboard Page</div>
);
}
}
export default connect()(Dashboard);
Currently my dashboard looks for cookie about authentication and update my store.But after adding custom route
there happens a redirection to login page
that's because my custom route doesnot find the updated store
since it is updated in dashboard. I am stuck here. I tried updating in my custom route but I added more confusion to myself. Any suggestion and solution is appreciated.
Thanks
Upvotes: 0
Views: 58
Reputation: 1065
If you post your Login
component, I could better answer the question.
Having said that, it is not the responsibility of the dashboard component to setAuthenticatedUser
, since, if they are able to navigate to the dashboard, it means they are ALREADY authenticated.
After a user logs in, you should call setAuthenticatedUser
, then redirect to the dashboard, that way your PrivateRoute
component won't force a needless redirect.
Upvotes: 2