I used react-error-boundary
to implement <ErrorBoundary>
by wraping it around the component that may throw an error
export default function App() {
const [query, setQuery] = useState("");
const handleReset = () => setQuery("");
return (
<div className="App">
<input
value={query}
onChange={(e) => {
setQuery(e.target.value);
}}
/>
<FormErrorBoundary onReset={handleReset} resetKeys={[query]}>
<Form query={query} />
</FormErrorBoundary>
</div>
);
}
function Form({ query }) {
if (query === "error") throw new Error("foo");
return <p>{query}</p>;
}
function FormErrorBoundary(props) {
return <ErrorBoundary FallbackComponent={ErrorFallBack} {...props} />;
}
function ErrorFallBack({ error, resetErrorBoundary }) {
return (
<div role="alert">
There was an error
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
the idea is that when we type error
in the input field the Form
component should throw an error and the error boundary is supposed to catch it and display an UI with an re-try button
However if I type error
in the input field, the app would still crash. Check out this screenshot.
Only after you click on x
to close it, you can see the error boundary is working and there is the retry button you can click on. But I thought the error boundary would prevent it from crashing. Did I implement it wrong or this is the expected behavior for error boundaries in React?
Live demo: https://codesandbox.io/s/error-boundary-bz2ir?file=/src/App.js