I'm making a login page. On componentDidMount(), it checks for a cookie and sets the state variable "redirect" to true if there is and vice versa. In my App render(), I am able to redirect to login component if "redirect" is true. However, after I did login or set the cookie, I am unable to redirect to my dashboard/landing page.
I only have two components, Dashboard and Login, Dashboard does not manipulate the state whatsoever except for Login, which sets the state "redirect" in the parent component App. Below is my code:
App.js
import 'bootstrap/dist/css/bootstrap.min.css';
import {BrowserRouter,Route,Switch,Redirect} from 'react-router-dom';
import Dashboard from './components/Dashboard';
import Login from './components/Login';
import Cookie from 'js-cookie';
import Nav from './components/Nav';
import Error from './components/Error';
class App extends Component{
state={
redirect:false
}
componentDidMount(){
if(Cookie.get("api")!=null){
console.log("There exists a cookie");
this.setState({
redirect:false
});
}else{
console.log("There is no cookie");
this.setState({
redirect:true
});
}
}
setCookie=()=>{
Cookie.set("api","Cookie");
console.log(Cookie.get("api"));
this.setState({
redirect:false
});
return <Redirect to="/"/>
}
render(){
return (
<BrowserRouter>
<div className="container">
<div className="row">
<div className="col-12 text-left mt-5">
<Nav/>
<Switch>
<Route exact path="/" render={()=>(
this.state.redirect?<Redirect to="/login"/>:<Dashboard/>
)}/>
<Route path="/login" render={()=>(
<Login setCookie={this.setCookie}/>
)}/>
<Route component={Error}/>
</Switch>
</div>
</div>
</div>
</BrowserRouter>
);
}
}
Login.js
class Login extends Component {
onClick=()=>{
this.props.setCookie();
}
render() {
return (
<div>
<h1>Login page!</h1>
<Button onClick={this.props.setCookie}>Set Cookie to Log In</Button>
</div>
);
}
}
By right,after pressing the set cookie button in Login, it should redirect to the Dashboard component.
Any idea how I could do that? Thank you for reading.