Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!