Reputation: 353
I´m trying to make fetch stop and alert if it returns that errorMessage,
so the ()=>this.toggleModal()
wont get executed.
handleSubmit(event){
const url = 'http://localhost:8000/issue/';
var issueid = 13900;
var issueid = document.getElementById("SearchTxt").value;
if(issueid == 0){
alert('Please insert IssueID or IssueKey')
}else{
var string2 = url+issueid;
fetch(string2)
.then(function(response) {
return response.json();
})
.then((myJson) => this.setState({example: myJson},() => this.toggleModal()))
}
}
JSON returned when issue doesn´t exist:
{
errorMessages: [
"Issue Does Not Exist"
],
errors: { },
}
Upvotes: 0
Views: 960
Reputation: 353
I´ve managed to fix it:
handleSubmit(event){
const url = 'http://localhost:8000/issue/';
var issueid = 13900;
var issueid = document.getElementById("SearchTxt").value;
if(issueid == 0){
alert('Please insert IssueID or IssueKey')
}else{
var string2 = url+issueid;
fetch(string2)
.then(function(response) {
return response.json();
})
.then((myJson) => this.conditionalChaining(myJson));
}
}
conditionalChaining(myJson) {
if (myJson.errorMessages == 'Issue Does Not Exist') {
alert('Issue doesn´t exist')
} else {
this.setState({example: myJson},() => this.toggleModal());
}
}
Upvotes: 0
Reputation: 1926
In case you want to cancel execution at return response.json();
you could do the following
handleSubmit(event){
const url = 'http://localhost:8000/issue/';
var issueid = document.getElementById("SearchTxt").value;
if(issueid == 0 || issueid == "" || issueid == undefined || issueid == null){
alert('Please insert IssueID or IssueKey')
return;
}
var string2 = url+issueid;
fetch(string2)
.then(function(response) {
const oJson = response.json();
// your validation of the json
if(oJson.hasOwnProperty("errorMessages") && oJson.errorMessages.includes("Issue Does Not Exist")
return Promise.reject(oJson.errorMessages[0]); // maybe use a better way instead of this hardcoded index
// set state if everything was properly done
this.setState({example: myJson},() => this.toggleModal())
})
.catch(error => {
// do some alert stuff
alert(error);
});
}
Upvotes: 1