Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update state with an error message in React?

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."

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please advise how to change the code so that error messages can be stored in state

>Solution :

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
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading