I'm trying to handle some error in my React app, but something must be escaping me because I can't seem to get it to work. Here is my code:
App.js
import ErrorBoundary from "./Error";
import ChildComponent from "./ChildComponent";
function App() {
return (
<ErrorBoundary>
<ChildComponent />
</ErrorBoundary>
);
}
export default App;
ChildComponent.jsx:
import React, { Component } from "react";
class ChildComponent extends Component {
state = {};
componentDidMount() {
console.log("componentDidMount called")
throw new Error("dummy error");
}
render() {
return <p>This will never be shown</p>;
}
}
export default ChildComponent;
Error.jsx:
class ErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.log(error.message);
}
render() {
if (this.state.hasError) {
console.log("rendering fallback ui")
return <h1>Error!</h1>;
}
console.log("rendering standard ui")
return this.props.children;
}
}
export default ErrorBoundary;
Console ouput:
> rendering standard ui
> componentDidMount called
> [JAVASCRIPT error logs]
> rendering fallback ui
> dummy error
> [APP CRASH]
Maybe I'm wrong here, but I would expect the app to open, run <ChildComponent />
, encounter the new Error("dummy error")
and render <ErrorBoundary />
's fallback UI, and STAY THERE. Instead it shows the fallback UI for a fraction of a second, then proceeds to crash the app and show the post-mortem. Why?