bourne2077
bourne2077

Reputation: 171

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

Upvotes: 1

Views: 1115

Answers (1)

Serhii
Serhii

Reputation: 439

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

Upvotes: 1

Related Questions