Last active
May 10, 2020 15:33
-
-
Save ntnbst/37a0254d21bc9bd40feaf78247fb2896 to your computer and use it in GitHub Desktop.
This gist has a simple implementation of error boundary (errors that occurs in react callstack unlike - promises or async calls)
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
// Using react-error-boundary library to handle custom error component in case of dom failure | |
// Error boundary will render the fallback component to its decendents in case of failure | |
// So we can add multiple error boundaries according to project | |
import { useState } from 'react' | |
import ReactErrorBoundary from 'react-error-boundary' | |
const ErrorBoundary = ReactErrorBoundary.ErrorBoundary | |
function ErrorFallback ({ error }) { | |
return ( | |
<div> | |
<p>Something went wrong!!</p> | |
<pre>{error.message}</pre> | |
</div> | |
) | |
} | |
function Bomb () { | |
throw new Error('💥 Caboom 💥') | |
} | |
function App () { | |
const [explode, setExplode] = useState(false) | |
return ( | |
<ErrorBoundary fallbackComponent={ErrorFallback}> | |
<div> | |
<div> | |
<button onClick={setExplode(true)}>💣</button> | |
</div> | |
<div> | |
<ErrorBoundary fallbackComponent={ErrorFallback}> | |
{explode ? <Bomb /> : 'Push the button'} | |
</ErrorBoundary> | |
</div> | |
</div> | |
</ErrorBoundary> | |
) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment