Created
January 30, 2020 22:24
-
-
Save luisrudge/885977a40d84eb179bca1a4f891653b6 to your computer and use it in GitHub Desktop.
trigger an error in a React ErrorBoundary from a hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const TheComponent = () => { | |
const [error, setError] = React.useState(); | |
React.useEffect(() => { | |
const asyncOperation = async () => { | |
// do something async | |
}; | |
asyncOperation().catch(e => { | |
setError(() => { | |
throw e; | |
}); | |
}); | |
}, []); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 theuseEffect
callback, we need to manually throw the error inside thesetState
callback. facebook/react#14981 (comment)