3
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?

1
  • 1
    put your data in state and update the state. Commented Aug 27, 2020 at 4:15

2 Answers 2

7

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>
    );
}

Sign up to request clarification or add additional context in comments.

Comments

0

Small suggestion: additionaly you can create your own hook for computing this in the different file and using it everywhere. Something like

const check = useCheck();
export function useCheck() {
    const [check, setCheck] = useState(null);

    useEffect(() => {
        (async () => {
            const data = await getData(props.path);
            setCheck(data);
        })();
    }, []);

    return check;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.