• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

84
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
  );
}
almost 3 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);
  }
}   

almost 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error