Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my function returning undefined despite printing out correctly

The code

the function returning

  async getData(key, setHook) {
    try {
      await AsyncStorage.getItem(key).then((response) => {
        console.log("getData response: " + response); // prints out correctly
        setHook(response); // sets my hook as undefined?
      })
    } catch(e) {
      console.log("AsyncStorage getData: error: " + e);
    }
  }

the function receiving


const key = 'key';

const Home = ( {navigation} ) =>  {
  ...
  const [totalBreaks, setTotalBreaks] = useState('0'); // the hook I use in the above function

 // on mount setCounter
 useEffect(() => {  
      setCounter();
 }, []);


 async function setCounter () {
    await asyncStorageInterface.getData(key, setTotalBreaks);
    console.log("total breaks: " + totalBreaks); // returns undefined on mount... when it shouldn't
    if(totalBreaks === null || totalBreaks === undefined) {
      await asyncStorageInterface.storeData(key, '0');
      await asyncStorageInterface.getData(key, setTotalBreaks);
    }
    console.log("total breaks: " + totalBreaks);
  }

Problem

I have no idea what the problem is… I spent almost 6 hours trying to fix this, can someone please help me out? And please explain what the problem is in depth if that’s possible so that I can document it somewhere. Thanks.

Edit

So my console.log is printing out the variable before the getData function runs. How do I get the console.log to wait for the hook value to be set? My if statement should only check the value of totalBreaks once the setTotalBreaks hook is set. That’s what I can’t figure out.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

your totalBreaks was read before you set it. it’s as simple as:

const result = {};
const {val} = result;
result.val = 'foo';
console.log(val); // you will still get undefined.

This is not related to asynchronous

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading