@xysfe/catch-react-error

react error boundaries

Usage no npm install needed!

<script type="module">
  import xysfeCatchReactError from 'https://cdn.skypack.dev/@xysfe/catch-react-error';
</script>

README

How to use

  1. install @xysfe/catch-react-error
npm install @xysfe/catch-react-error --save
  1. Install ES7 Decorator babel plugin
npm install --save-dev @babel/plugin-proposal-decorators
npm install --save-dev @babel/plugin-proposal-class-properties
  1. babel plugin configuration
{
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }]
  ]
}
  1. import @xysfe/catch-react-error
import catchreacterror from "@xysfe/catch-react-error";
  1. Use @catchreacterror on class component
@catchreacterror()
class Count extends React.Component {
  render() {
    const { count } = this.props;
    if (count === 3) {
      throw new Error("count is three");
    }
    return <h1>{count}</h1>;
  }
}
  1. Use @catchreacterror on functionc component
function Count({ count }) {
  if (count === 3) {
    throw new Error("count is three");
  }
  return <h1>{count}</h1>;
}
const SaleCount = catchreacterror()(Count);
  1. Add a CustomErrorBoundary component
// First, create an normal Error Boundary Component and change it
class CustomErrorBoundary extends React.Component {
  constructor (props) {
    super (props);
    this.state = {hasError: false};
  }
  static getDerivedStateFromError (error) {
    return {hasError: true};
  }
  componentDidCatch (error, errorInfo) {
    //do something as needed
    reportToMyLogService (error, errorInfo);
  }
  render () {
    if (this.state.hasError) {
      return <h1> Something with my app,fallback ui. </ h1>;
    }
  }
    return this.props.children;
  }
}
// Second, pass it as the argument
@catchreacterror(CustomErrorBoundary)
class Count extends React.Component {}

or

const SaleCount = catchreacterror(CustomErrorBoundary)(Count);