Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to catch fetch errors in React?

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?

like image 636
Vic Avatar asked Nov 03 '17 15:11

Vic


1 Answers

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

like image 144
Anvesh Checka Avatar answered Oct 09 '22 19:10

Anvesh Checka