I have a simple react component that looks like this:
class Test extends React.Component {
componentDidMount() {
fetch('/some-url-here')
.then((data) => {
this.setState({ data });
})
.catch(() => {
alert('failed to fetch');
});
}
render() {
// render the data here
}
}
The problem with this is that the catch
doesn't just catch fetch errors. It also catches any exceptions thrown in render
! What would be the correct way to create a simple component that fetches some data and handles fetch errors?
class Test extends React.Component {
componentDidMount() {
fetch('/some-url-here')
.then((data) => {
this.setState({ data });
}, (error) => {
if (error) {
// handle error here
}
});
}
render() {
// render the data here
}
}
If you use a catch instead of second callback, any errors that might've occurred during setState method would be left unhandled. So you can capture render method errors in your own way. For more info, give a reading on this tweet by Dan Abramov.
Dan's Tweet
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With