Problem:
I am trying to implement error boundary in React. But for some reason it isn’t working. Here is the code:
ErrorBoundary.js
import React from 'react';
class ErrorBoundary extends React.Component {
// Equivalent to:
// const [hasError, setHasError] = useState(false);
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.error(error);
console.info({ errorInfo });
}
render() {
if (this.state.hasError) {
return this.props.fallback || null;
}
return this.props.children;
}
}
export default ErrorBoundary;
Counter.js
import React from 'react';
const Counter = ({ user }) => {
if (!user) {
throw new Error('Error Some');
}
return <div>{user.toUpperCase()}</div>;
};
export default Counter;
App.js
import React from 'react';
import ErrorBoundary from './ErrorBoundary';
import Counter from './Counter';
function App() {
return (
<ErrorBoundary fallback={<div>this is fallback UI</div>}>
<Counter />
</ErrorBoundary>
);
}
export default App;
Here is the live code.
Solution:
it will work in production, the reason why you don’t see the fallback ui is because it’s under the error overlay iframe, you can see the fallback ui if you close the error overlay ( X on the top right ) or add
iframe { display: none;}
to your style.css
( and import the style.css )
here’s an updated code https://stackblitz.com/edit/stackblitz-starters-funblb?file=src%2Fstyle.css