[SOLVED] Calling a function when opening a react-native screen

Issue

I’m trying to load a JSON from AsyncStorage every time a user opens one of my react-native screens (I’m using StackNavigator). This JSON contains information on what my states should be set to.

How can I call a function that runs every time this screen is opened?

Further info:
I’ve written a function that updates my states according to a JSON loaded from AsyncStorage. The function works perfectly when called from a button, but when the function is called from render(), part of my screen freezes and some buttons are not touchable anymore. Strangely only TextInput still works.

Solution

use componentWillMount() method. This will execute automatically before render() method gets triggered.

class Sample extends Component{
    state = {data : []};
    componentWillMount(){
        this.setState({data : inputObject});
    }
    render(){
        return(
            <View>
            //you can render the data here
            </View>
        );
    }
}

Reference: https://facebook.github.io/react/docs/react-component.html#componentwillmount

Answered By – divine

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.