Home > Mobile >  Why is my function returning undefined despite printing out correctly
Why is my function returning undefined despite printing out correctly

Time:12-29

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.

CodePudding user response:

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

CodePudding user response:

Are you sure you're receiving undefined? I think you are doing things just right but the problem is you are trusting that last console.log you have. It is printing undefined, but actually it's printing before you set it's actual value, that's why it's undefined. If this is not the case let me know in a comment, I'll try it answer as soon as possible

  • Related