I am troubled with redirect after login. As I know Fetch API has no concept of handling this. I tried to use React-router-dom but it is not working. I don't know what I am doing differently. I am trying to learn basic react, develop an application which is fully authenticated.
I did this
import { BrowserRouter as Router, Route, Redirect} from 'react-router-dom';
import Dashboard from './Dashboard';
This is the state
this.state = {
redirect: false,
username: '',
l_password: ''
}
The Fetch API and setRedirect function
setRedirect =() =>{
this.setState({
redirect: true
});
}
handleLogin =(event) =>{
event.preventDefault();
fetch('/oauth/token',
{
method: "POST",
headers:{
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body:`grant_type=password&username=${this.state.username}&password=${this.state.l_password}&client_id=4&client_secret=LT7raDKvPwIUrDFJBISlhpzAXu6cSYiLBGhrUmTm&scope=*`
}
)
.then(response =>
response.json()
)
.then(responseJson => {
const returnObj = responseJson;
console.log(returnObj);
sessionStorage.setItem('resData', JSON.stringify(returnObj));
console.log(this.state.redirect);
if(this.state.redirect === true){
return (
<Router><Route path="/dashboard" component={Dashboard} /></Router>
);
}
else{
<Redirect to="/" />
}
});
this.setState({
username: '',
l_password:''
});
}
The form
<Form onSubmit={this.handleLogin}>
<Form.Group controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" placeholder="Enter email"
autofoccus="true"
autoComplete="new-email"
onChange= {this.ChangeText}
name="username"
value={this.state.username}
/>
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password" placeholder="Password" autoComplete="new-password"
onChange= {this.ChangeText}
name="l_password"
value={this.state.l_password}
/>
</Form.Group>
<Button
onClick={this.setRedirect.bind(this)}
variant="primary" type="submit" size="lg" block>
Login
</Button>
<Form.Group controlId="formBasicChecbox">
<Form.Check type="checkbox" label="Remember" />
<a href="#" style={{float:'right', marginTop:-23}}>Forgot Password?</a>
</Form.Group>
<div id="error"></div>
<div className="clear-fix"></div>
<hr/>
</Form>
What I intend to achieve is to redirect the page to dashboard if redirect is true otherwise the home
