Skip to content

Instantly share code, notes, and snippets.

@luisrudge
Created January 30, 2020 22:24
Show Gist options
  • Save luisrudge/885977a40d84eb179bca1a4f891653b6 to your computer and use it in GitHub Desktop.
Save luisrudge/885977a40d84eb179bca1a4f891653b6 to your computer and use it in GitHub Desktop.
trigger an error in a React ErrorBoundary from a hook
const TheComponent = () => {
const [error, setError] = React.useState();
React.useEffect(() => {
const asyncOperation = async () => {
// do something async
};
asyncOperation().catch(e => {
setError(() => {
throw e;
});
});
}, []);
};
@luisrudge
Copy link
Author

ErrorBoundaries will catch any sync error that might happen inside your render functions. Because of the way hooks work, errors will not throw by default from inside a hook.
Since we can't await asyncOperation() inside the useEffect callback, we need to manually throw the error inside the setState callback. facebook/react#14981 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment