1

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
  );
}
2
  • 1
    I love it when my code comes back to haunt me :) Commented Oct 31, 2021 at 11:57
  • I've seen this code before. Isn't it Link Commented Oct 31, 2021 at 12:02

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.