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

156
Views
Handling errors in useEffect when fetching data from an API

I have a react app that is fetching data from a GraphQL API. I'm doing this inside a useEffect hook. What is the best way to implement error handing? For now I just want to console log any returned errors.

I tried using try.. catch, but any errors returned from the API are not being console logged. What is the correct way of using try/catch in useEffect? Or what would be a better way of doing this?

async function contactAPI() {
  return await axios({
    url: 'https://graphqlexample.com/products/api',
    method: 'post',
    data: {
      query: `
      QUERY GOES HERE
        `
    }
  })
}

function App() {  
  const [products, setProducts] = useState([]);

  try {
    useEffect(() => {
      async function getData() {
        const resp = await contactAPI();
        setProducts(resp.data.data.products);
      }
      getData();
    }, []);    
  } catch (err) {
    console.log("there was an error:", err);
  }

  return (
    // JSX GOES HERE
  );
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You should cover with try-catch the exact line which may cause a problem, not a useEffect nor getData, so try this instead:

async function getData() {
  try {
    const resp = await contactAPI();
    setProducts(resp.data.data.products);
  } catch (err) {
    console.err("there was an error:", err);
  }
}   

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!