Thursday, 19 December 2019

javascript - Redux-form - Redirect after server response

I am using redux-form in react and I would like to redirect to other page after succesful server response ( res 200) . Here is full code with my class LoginForm:



class LoginForm extends React.Component {

state = {
redirectToNewPage: false
}

handleSubmit=({email='',password=''})=>{
let error={};
let isError=false;
if(email.trim()===''){
error.email='Required';
isError=true;
}
if(password.trim()===''){
error.password='Required';
isError=true;
}
if(isError){
throw new SubmissionError(error);
}
else{
//this.setState({ redirectToNewPage: true }); // <--- it will redirect
fetch('/auth', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: password,
})
})
.then( function(res){
console.log(res.status);
if(res.status==200){
console.log("REDIRECTING...");
//this.setState({ redirectToNewPage: true }); // It will show error unknow function

}
else{
console.log("ERROR");
}
})


}
}

static propTypes={
handleSubmit:React.PropTypes.func
}

render(){
const {handleSubmit}=this.props;
if (this.state.redirectToNewPage) {
return (

)
}
return(


Login







)
}

};


The problem is inside handleSubmit method. I can't use (this.setState()) inside .then after fetch:



.then( function(res){
console.log(res.status);
if(res.status==200){
console.log("REDIRECTING...");
//this.setState({ redirectToNewPage: true }); // It will show error unknow function

}
else{
console.log("ERROR");
}


I got an error :




Uncaught (in promise) TypeError: Cannot read property 'setState' of
undefined




Have you got any ideas how to do that?

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...