Reputation: 1216
I am still a beginner in React programming and I am quite confused on how to do protected routing.
So, I have this in my App.js
<Router>
<div className="App">
<Route exact path="/" component={Loginscreen} />
<PrivateRoute path="/upload" component={UploadScreen} />
<PrivateRoute path="/materials" component={Materials} />
</div>
</Router>
in which the landing page is the Log In Screen.
But what I want to do is that you can't visit /Upload, and /materials if you are not logged in.
Now, To be able to know that a person is logged in, I have this onSubmit
func on LogIn.js
onSubmit = (e) => {
e.preventDefault();
var apiBaseUrl = "http://127.0.0.1:8000/api/auth/login";
var self = this;
var payload={
"email":this.state.email,
"password":this.state.password
}
var config = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
withCredentials: false
}
axios.post(apiBaseUrl, payload, config)
.then(function (response) {
console.log(response);
if(response.status == 200){
console.log("Login successful");
}
else if(response.status == 204){
console.log("Username password do not match");
alert("username password do not match")
}
else{
console.log("Username does not exists");
alert("Username does not exist");
}
})
.catch(function (error) {
console.log(error);
});
}
I was thinking what my PrivateRoute
would look like that would check if the person is logged in according to the response.status
in Login.js
Upvotes: 0
Views: 103
Reputation: 331
Create a isLoggedIn
state variable in App.js and use it to decide whether or not to render other routes. Like this,
render() {
let privateRoutes = null;
if(this.state.isLoggedIn){
privateRoutes =(
<Route path="/upload" component={UploadScreen} />
<Route path="/materials" component={Materials} />
);
}
<Router>
<div className="App">
<Route exact path="/" component={Loginscreen} />
{privateRoutes}
</div>
</Router>
}
Needless to say, isLoggedIn
needs to be updated based on the value of onSubmit
method
Upvotes: 1