Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda