0

As per the new react 16 release doc it says

"React 16 prints all errors that occurred during rendering to the console in development, even if the application accidentally swallows them."

I have a Parent component and a Child component. I have triggered an error in then block of promise. But it will call catch method of the promise, componentDidCatch of parent is not getting called. I am not sure whether this the expected behaviour.

Here is the jsfiddle https://jsfiddle.net/john1jan/Luktwrdm/14/

class Parent extends React.Component {  
  constructor(props){
    super(props);
    this.state={hasError:false}
  }

  render() {
    if(this.state.hasError){
      return <div>Something went wrong</div>
    }

    return (
      <div>
        <h1>I am parent</h1>
        <Child></Child>
      </div>
    );
  }
  componentDidCatch(error,errorInfo){
    this.setState({
      hasError:true
    })
  }
}

class Child extends React.Component {

  render() {
    return (
      <div>
        <h1>I am child</h1>
      </div>
    );
  }

  componentDidMount(){
    fetch("https://jsonplaceholder.typicode.com/posts").then((response) => {
      throw new Error("I am the error in promise");
    }).catch((error)=>{
      console.log("Error caught in catch",error);
    })
    ;
  }
}

ReactDOM.render(<Parent name="world"/>, 
document.getElementById('container'));
Chris
  • 57,622
  • 19
  • 111
  • 137
John
  • 8,846
  • 8
  • 50
  • 85
  • 2
    Because the error was not in the component, so there is nothing to catch. In fact, you have already caught the exception yourself and chose to log it to the console. If you want to pass it on, simply re-throw the error in your catch. – Stephan Bijzitter Oct 23 '17 at 11:55
  • the error is in the component life cycle method right ? – John Oct 23 '17 at 11:57
  • More over the doc says "React 16 prints all errors that occurred during rendering to the console in development, even if the application accidentally swallows them.". What if i forgot to add catch block after then ? – John Oct 23 '17 at 11:58
  • As soon as you catch an error, the error is considered handled and as such there is no error anymore. – Stephan Bijzitter Oct 23 '17 at 12:17

2 Answers2

6

Just want to point out to anyone who comes into this question looking for an answer.

React 16 prints all errors that occurred during rendering to the console in development, even if the application accidentally swallows them.

componentDidCatch will only trigger within the rendering lifecycle methods.

Since your error is thrown inside the promise. It is asynchronous and won't be part of the rendering lifecycle so you will need to handle the error yourself.

Kenneth Truong
  • 3,882
  • 3
  • 28
  • 47
2

You're catching the error and the return of a catch is a promise, so you don't have error anymore, if you remove the .catch on your fetch in componentDidMount, this should work!