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

229
Visualizações
Error thrown but not caught in useEffect try-catch?

I'm new to react. Here I am fetching data from an API and checking if there are null values present in the one of the attributes. If so, the code throws a 'Module not found' error. The error is being thrown but not caught in the catch block. The log in the catch block does not show up when the error is thrown. What am i doing wrong??

  useEffect(() => {
    let isMounted = true;
    const fetchData = async () => {
      try { 
        const res = await fetch(url);
        if (!res.ok) {
          throw Error("Unable to request data for this resource");
        }
        if (isMounted) {
          const data = await res.json();
          if (data.modInfo === null) {
            throw Error("Module not found");
          }
          setmodInfo(data.modInfo);
          setIsLoading(false);
          setError(null);
        }
      } catch(err) {
        setIsLoading(false);
        setError(err.message);
        console.log('err', err.message);
      }
    };

    fetchData();
    return () => {
      isMounted = false;
    };
  }, [url]);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Might it work the way you intend if you make isMounted stateful?

Move this out of the useEffect:

let isMounted = true;

And change to:

const [isMounted, setIsMounted] useState(true);

And change this:

return () => {
  isMounted = false;
};

to:

return () => {
  setIsMounted(false);
};
about 4 years ago · Juan Pablo Isaza Relatório

0

Issue was with the order of state updates on isLoading and error as well as my conditions for conditional rendering of child components.

In useEffect():

setIsLoading(false);
setError(err.message);
console.log('err', err.message);

In return statement of the component:

  return (
    <>
      {isLoading && <h2>Loading...</h2>}
      {error && <h2>Module not found</h2>}
      {!isLoading && !error && (
      ...
  )

My guess is that once isLoading was set to true the third condition passed before error could be updated since state updates are asynchronous. Fixed this by updating error before isLoading in the catch block and checking for error first in the render.

Fixed useEffect():

 useEffect(() => {
    let isMounted = true;
    const fetchData = async () => {
      try { 
        const res = await fetch(url);
        if (!res.ok) {
          throw Error("Unable to request data for this resource");
        }
        if (isMounted) {
          const data = await res.json();
          if (data.modInfo === null) {
            console.log("found null")
            throw Error("Module not found");
          }
          setmodInfo(data.modInfo);
          setError(null);
          setIsLoading(false);
        }
      } catch(err) {
        setError(err.message);
        console.log(err.message);
        setIsLoading(false);
      }
    };

    fetchData();
    return () => {
      isMounted = false;
    };
  }, [url]);

Fixed return statement:

  return (
    <>
      {error && <h2>Module not found</h2>}
      {isLoading && <h2>Loading...</h2>}
      {!isLoading && !error && (
      ...
)
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