Reputation: 105
In compoenntDidMount lifecycle, I am fetching an API, getting data and catching the potential error. I can get the data properly. However, In catching the error stage, I would like to update my state as well but so weird, I cannot.
In state I have an isError boolean. It is false by default. When I change the api url in fetch, I can see console.log message, but my isError is still false.
componentDidMount() {
fetch(
"url"
)
.then(response => response.json())
.then(data => {
this.setState({
data1: data.response.venues,
});
})
.catch(error => {
this.setState({isError: true})
console.log("bla bla", error)
});
}
Upvotes: 0
Views: 700
Reputation: 83
Nicholas Tower is right i think.
First are you using ES6
or redux
?
Secondly try to pass your api call into an async function.
Catch the call with await
to avoid setState execution as nicholas said.
If you use redux call your api with an action is a better practice. A little example here : https://redux.js.org/advanced/asyncactions
maybe like that :
{
try {
const ret = await my_action(*);
}
catch (error) {
this.setState({
isError: true,
errorInState: error,
});
}
}
Sometimes the speed of execution surpasses some slower actions and creates creates incredible bugs.
Upvotes: 1