React

by janeklb

HTML

<div id="app"></div>

React

// Example

const ComponentThatThrows = ({ value }) => {
	if (value === "error") {
  	throw new Error("Bang!")
  }
  return `Thanks, you provided: '${value}'`;
}


const ComponentWithErrorBoundary = ({ value }) => {
  return (
    <div>
      <ErrorBoundary fallback={<span>Oooops!</span>} resetKeys={[value]}>
        <ComponentThatThrows value={value} />
      </ErrorBoundary>
    </div>
  );
};

const Example = () => {

  const [externalState, setExternalState] = React.useState();
  const onChange = React.useCallback((event) => setExternalState(event.target.value), []);
  
  return (
    <div>
      Type something: <input onChange={onChange} />
      <ComponentWithErrorBoundary value={externalState} />
    </div>
  );
};


const react = React;

// couldn't get the module to load here so the following is just copy-pasted from
// https://unpkg.com/browse/[email protected]/dist/react-error-boundary.cjs.js

const ErrorBoundaryContext = react.createContext(null);

const initialState = {
  didCatch: false,
  error: null
};
class ErrorBoundary extends react.Component {
  constructor(props) {
    super(props);
    this.resetErrorBoundary = this.resetErrorBoundary.bind(this);
    this.state = initialState;
  }
  static getDerivedStateFromError(error) {
    return {
      didCatch: true,
      error
    };
  }
  resetErrorBoundary() {
    const {
      error
    } = this.state;
    if (error !== null) {
      var _this$props$onReset, _this$props;
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      (_this$props$onReset = (_this$props = this.props).onReset) === null || _this$props$onReset === void 0 ? void 0 : _this$props$onReset.call(_this$props, {
        args,
        reason: "imperative-api"
      });
      this.setState(initialState);
    }
  }
  componentDidCatch(error, info) {
    var _this$props$onError, _this$props2;
    (_this$props$onError = (_this$props2 =...