Created
January 26, 2023 12:30
-
-
Save jdelStrother/431d60131eaa09cdb62b1215ac07ad00 to your computer and use it in GitHub Desktop.
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
// This prevents error propagation, so that Storybook doesn't show its onerror report, | |
// and the browser (or jest) doesn't display console.error messages | |
const SilenceConsole = (props: { children: JSX.Element }) => { | |
const [ready, setReady] = React.useState(false); | |
React.useLayoutEffect(() => { | |
function handler(e: ErrorEvent) { | |
// prevent React's listener from firing | |
e.stopImmediatePropagation(); | |
// prevent the browser's console error message | |
e.preventDefault(); | |
} | |
window.addEventListener("error", handler, true); | |
// Sadly react still insists on logging the error, haven't found a way of | |
// suppressing that without resorting to overriding console.error() | |
const originalConsoleError = console.error; | |
console.error = () => {}; | |
setReady(true); | |
return () => { | |
console.error = originalConsoleError; | |
window.removeEventListener("error", handler, true); | |
}; | |
}, []); | |
return ready ? props.children : null; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment