javascriptandroidreact-nativeasynchronousasyncstorage

How to get value from async function in react-native?


function CategoryCard (props) {

    const [done, setDone] = React.useState(null);
    let check;

    React.useEffect(() => {
        async function checkData() {
            check = await getData(props.path);
            // prints CORRECTLY
            console.log(check);
        }
        checkData();
    //prints INCORRECTLY
        console.log(check);
        setDone(true);
    }, []);

    return (

        <View>
        {done ? (
            <Text>{check}</Text>
        ):(
            <View style={[styles.container, styles.horizontal]}>
                <ActivityIndicator size="large" color="#99ff99" />
            </View>
        )}
        </View>
    );
}

How can I get a value from an async function into my regular function in react-native? In the above code, the first console.log prints the expected values, but the second one gives undefined, as if the async function never had any effect on the variable check. I need the value of check from getData(props.path) in order to display it in the <Text> component.

Any ideas?


Solution

  • Put it in the state.

    function CategoryCard (props) {
    
        const [check, setCheck] = React.useState(null);
    
        React.useEffect(() => {
            async function checkData() {
                const data = await getData(props.path);
                setCheck(data);
            }
            checkData();
    
        }, []);
    
        return (
    
            <View>
            {check ? (
                <Text>{check}</Text>
            ):(
                <View style={[styles.container, styles.horizontal]}>
                    <ActivityIndicator size="large" color="#99ff99" />
                </View>
            )}
            </View>
        );
    }