Home > Blockchain >  Why useState variable gets undefined inside try catch statement in an asynchrone function?
Why useState variable gets undefined inside try catch statement in an asynchrone function?

Time:02-24

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 ?

CodePudding user response:

I think this gonna work

 useEffect(() => {
      const fetchData = async () => {
        const data = await fetchSomething();
        setMyObject(data);
      }
If(!myObject)
      fetchData();
    }, [myObject]);

CodePudding user response:

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;
      };
  • Related