Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

203
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda