Call Function Without Onpress React Native
I'm new to react native. I am trying to get 'Key' without using the onpress in button. I just want to get a 'key', when i could open component. How it could be possible? import Re
Solution 1:
You can simply get your key value with componentDidMount. As you should know, when the App runs and comes to the current screen, there is a flow of methods will be called before and after rendering the render function. So ComponentDidMount comes after render function is called. So since you need to only display the key value, just follow below code.
constructor(props) {
super(props);
this.state = {
myKey:''
}
}
getKey = async() => {
try {
const value = awaitAsyncStorage.getItem('@MySuperStore:key');
this.setState({ myKey: value });
} catch (error) {
console.log("Error retrieving data" + error);
}
}
componentDidMount(){
this.getKey();
}
render() {
return (
<Viewstyle={styles.container}><Buttonstyle={styles.formButton}onPress={this.getKey.bind(this)}title="Get Key"color="#2196f3"accessibilityLabel="Get Key"
/><Text >
Stored key is {this.state.myKey}
</Text></View>
)
}
Whenever render function being called, in that time, still key value is not set. So, this.state.myKey
would be just Stored key is
. But after that, once the componentDidMount called, it sets the myKey value and change states. Which will trig render function to render everything again. That would show your key value within the text component eventually without touching any button.
Post a Comment for "Call Function Without Onpress React Native"