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

211
Visualizações
Why useState variable gets undefined inside try catch statement in an asynchrone function?

I create a hook that manages the state of a single object with fetch to api. This hook exposes function to interact with this object.

// the hook
const useMyHook = () => {
    const [myObject, setMyObject] = useState(null);
    
    useEffect(() => {
      const fetchData = async () => {
        const data = await fetchSomething();
        setMyObject(data);
      }
      fetchData();
    }, []);

    const updateMyObject = async () => {
        console.log(myObject);                // log : { ... }
        try {
            console.log(myObject);            // log : undefined
            // ...
        } catch(err) {
            // ...
        }
    };

    return {
        updateMyObject,
        myObject
    };
};

Then i use this hook inside a component and trigger updateMyObject() with a button.

// the component
const MyComponent = () => {
    const { myObject, updateMyObject } = useMyHook();

    return (
        <button onClick={updateMyObject}>
            Click me
        </button>
    );
};

How is this possible that before the try catch block the log is clean and inside the block i get undefined ?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Your code is perfectly alright !! There could be a problem in the fetchSomething() method. Ideally, it should return data, but it's not doing the same job.

Here is a small example. You can give it a try.

 const fetchSomething = async () => {
        const response = await fetch(
          "https://jsonplaceholder.typicode.com/posts/1"
        ).then((res) => res.json());
        return response;
      };
about 4 years ago · Juan Pablo Isaza Relatório

0

I think this gonna work

 useEffect(() => {
      const fetchData = async () => {
        const data = await fetchSomething();
        setMyObject(data);
      }
If(!myObject)
      fetchData();
    }, [myObject]);
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