0

So I await for the promise to fulfil, then I want to use the resulting data outside of .then() or the async function.

function HomeScreen() {

    const userData = async () => { 
        await AsyncStorage.getItem("user_nicename")     
    }

    return (
        <View style={styles.container}>      
            <Text>Hello, { userData() } </Text>  //*I want to use it here for example*//

            <Button 
                style={styles.buttonLogin}
                onPress={() => navigation.navigate('LoginScreen')}
                title='Logout'
            />      
        </View>
    ) 
}

export default HomeScreen;

of course my code will throw an error because userData() is a 'promise object'. I just want the string value, which I have no problems accessing inside .then(data => ... ). But how do I access it outside so I can use it somewhere else?

Rollor
  • 601
  • 1
  • 7
  • 17

1 Answers1

2

You to use useState and useEffect

import { useState, useEffect } from "react";

function HomeScreen() {
    const [userData, setUserData] = useState(undefined);

    useEffect(() => {
        (async () => {
            setUserData(await AsyncStorage.getItem("user_nicename"));
        })();
    }, []);

    return (
        <View style={styles.container}>      
            <Text>Hello, { userData } </Text>

            <Button 
                style={styles.buttonLogin}
                onPress={() => navigation.navigate('LoginScreen')}
                title='Logout'
            />      
        </View>
    ) 
}

export default HomeScreen;
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34