Last active
December 5, 2022 14:48
-
-
Save amitsingh-007/2576029ca785314019069ab49aa8f7ef to your computer and use it in GitHub Desktop.
Monkey patch console.error() to process React hydration errors
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
//Update this array to catch more errors | |
const HYDRATION_ERROR_MSGS = [ | |
"Warning: Did not expect server HTML to contain", | |
"Warning: Text content did not match. Server", | |
]; | |
//Can use any npm packag instead of this | |
const interpolate = (template, params) => | |
params.reduce((p, c) => p.replace(/%s/, c), template); | |
const isReactHydrationError = args => { | |
const errorArg = args && args[0]; | |
return ( | |
errorArg && | |
typeof errorArg.includes === "function" && | |
HYDRATION_ERROR_MSGS.some(msg => errorArg.includes(msg)) | |
); | |
}; | |
const logHydrationError = args => { | |
args[0] = `ReactHydrationError - ${args[0]}`; | |
const [template, ...params] = args; | |
const error = interpolate(template, params); | |
//Function to log this error in the desired error logging channel | |
reportError({ error }); | |
}; | |
const patchConsoleError = () => { | |
//Save reference to original error() function | |
const { error } = console; | |
console.error = function () { | |
if (isReactHydrationError(arguments)) { | |
logHydrationError(arguments); | |
} | |
error.apply(console, arguments); | |
}; | |
}; | |
export default patchConsoleError; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, I have added a demo here: https://github.com/amitsingh-007/react-hydration-error and also hosted it(which is meaningless since we can only catch it in dev env). I have added all the steps on how to run this on your local machine. Let me know if you still are having some trouble with it. Peace