I am getting data from AsyncStorage
and I am able to console.log
it on first render, but when I try to display a value a get undefined
error because my state has not been updated.
I am using three console.log
(C1,C2,C3) to understand the issue but I am stuck. What am I missing?
This is my function to get the data:
const [fullData, setFullData] = useState({})const getAllData = async () => { const allKeys = await AsyncStorage.getAllKeys(); const result: any = {}; try { const storage = await AsyncStorage.multiGet(allKeys); storage.map(e => { result[e[0]] = e[1]; }); } catch (e) { console.log(e); } for (let i in result) { result[i] = JSON.parse(result[i]); } console.log('C1', result); setFullData(result); };
This is how I pretend to show the data on first render:
const ShowData = () => { try { console.log("C2",fullData) return (<View ><Text style={styles.kanji}>{fullData["0"].kanji}</Text></View> ); } catch (e) { return <Text>Error</Text>; } };
This is my useState
to run on first render.
useEffect(() => { getAllData(); console.log('C3', fullData); }, []);
This is how my log output looks like:
LOG C3 {} LOG C2 {} LOG C1 {"0": {"anki": "0", "id": "0", "kanji": "猫", "meaning": "Gato", "reading": "猫"}, "10": {"anki": "100", ...