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.
>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