Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
};

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!