Hi I was trying to update state depending on the error message caught. My code is:
const [errors,setErrors] = useState("Blah blah");
const verifyIfObject = (object) => {
try {
if (object === "object") {
return true;
} else {
const errMsg = `Error: ${object} is not a js object...`;
throw errMsg;
}
}
catch (e) {
console.log(e);
setErrors(e);
}
};
When executing the code with error I get the error message in console:
"Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop."
Please advise how to change the code so that error messages can be stored in state
CodePudding user response:
a try/catch block needs to be used in an async function. You may simplify your function like this:
const [errors,setErrors] = useState("Blah blah");
const verifyIfObject = (object) => {
if (object !== "object") {
setErrors(`Error: ${object} is not a js object...`);
return false
}
return true
};