I'm trying to get some data from a server with fetch request. Some times network will fail or similar other things happens and I want to have a timeout to prevent further errors and also have a better experience.
Actually I want to wait for 20 seconds and if I don't get any response I want to show an error and also break the fetch request.
I have a loading modal which I can close it by timeout but I want to break the fetch request either.
here is my fetch request code:
_testPress = async () => {
//setTimeout(() => {this.setState({loading: false})}, 20000)
this.setState({loading : true})
fetch(getInitUrl('loginUser'), {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
password : this.state.password,
email : this.state.emailAddress,
}),
}).then(response => Promise.all([response.ok, response.status ,response.json()]))
.then(([responseOk,responseStatus, body]) => {
if (responseOk) {
//console.log(responseOk, body);
this._signInAsync(body.token);
// handle success case
} else {
console.log(responseStatus);
this.setState({
showAlert : true,
alertType : true,
alertMessage : body.message
});
}
})
.catch(error => {
console.error(error);
// catches error case and if fetch itself rejects
});
}
I used setTimeout to close loading module but it wont stop actual request which I want it to stop after 20 seconds.
Please help me with your advice. thx.