Tuesday, August 21, 2018

componentDidCatch example

The componentDidCatch life-cycle method is invoked when an exception is thrown in its child component hierarchy. Components which implement componentDidCatch are called Error Boundary components. These components act as catch {} blocks to capture exceptions.

The following example has 3 components
ErrorBoundaryComponent - Implements componentDidCatch, acts as a catch {} block to capture errors in child components.
ChildComponent - Actual UI component, encapsulated in ErrorBoundaryComponent
RootComponent - This is the bootstrap component which launches the application.

In the child component we explicitly throw an error, to see how it is captured and handled in the ErrorBoundary component.
throw new Error("Custom error");

import React, {Component} from 'react';
import ReactDOM from 'react-dom';

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

  componentDidCatch(error, info) {
    this.setState({ hasError: true });
console.log (error); // log errors here
  }

  render() {
    if (this.state.hasError) {
      return <h4>Something went wrong, please try later.</h4>;
    }
    return this.props.children;
  }
}

class ChildComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
show: false
};
  }

  render() {
throw new Error("Custom error");
return (
  <div>
<div>
<span>This component in encapsulated in an Error Boundary</span>
</div>
  </div>
);
  }
}

function RootComponent() {
  return (
    <ErrorBoundaryComponent>
      <ChildComponent />
    </ErrorBoundaryComponent>
  );
}

ReactDOM.render(<RootComponent />, document.getElementById('app'));

Search Flipkart Products:
Flipkart.com

No comments: