Everyone, Here is my dirty code.
const parseJson = async value => {
try{
const parsedData = await JSON.parse(value);
console.log('2', parsedData);
return parsedData;
}catch(e){}
}
const getAuthStateData = async () => {
try{
const storedAuthData = await AsyncStorage.getItem('authState');
console.log('1', storedAuthData);
return storedAuthData != null ? parseJson(storedAuthData) : null;
}catch(e){}
}
useEffect(() => {
const authStateData = getAuthStateData();
console.log('3', authStateData);
}, [])
Expected console state order is
1, 2, 3
Real console state order is
3, 1, 2
The authState has too many data. so get it from Asyncstorage (if you are not familiar with it, you can assume it like as localstorage) takes some time, and also parsing it to json takes 500 ms. so I need to wait all of them. This is basic of javascript concept: async, sync, promise. Please help me, seniors!
You are not awaiting the call to getAuthStateData in your useEffect callback, so it runs asynchronously, and the rest of the callback keeps running synchronously until the runtime has time to run the other tasks you've given it.
I think you meant to write this instead:
useEffect(async () => {
const authStateData = await getAuthStateData();
console.log('3', authStateData);
}, []);
The main issue is the missing await before getAuthStateData(), but you're missing some dependencies and cleanup as well. See inline comments:
const parseJson = (value) => { //not async -- see next comment
try{
const parsedData = JSON.parse(value); //JSON.parse is not an async method, so there's no reason to await here
console.log('2', parsedData);
return parsedData;
}catch(e){
console.error(e);
}
}
const _getAuthStateData = async () => {
try{
const storedAuthData = await AsyncStorage.getItem('authState');
console.log('1', storedAuthData);
return storedAuthData != null ? parseJson(storedAuthData) : null;
}catch(e){
console.error(e);
}
}
//get a memoized version of the callback
const getAuthStateData = React.useCallback(_getAuthStateData,[])
useEffect(() => {
async function asyncFunc() {
const authStateData = await getAuthStateData();
console.log('3', authStateData);
}
asyncFunc(); //prevent a linter error about using an `async` function directly inside `useEffect` by wrapping an async function and calling it
},[getAuthStateData]) //because we use getAuthStateData, it should be a dependency -- that's why we memoized it above