Reputation: 79
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 React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
TextInput,
Button,
View,
AsyncStorage
} from 'react-native';
export default class History extends Component {
constructor(props) {
super(props);
this.state = {
myKey: null
}
}
async getKey() {
try {
const value = await AsyncStorage.getItem('@MySuperStore:key');
this.setState({ myKey: value });
} catch (error) {
console.log("Error retrieving data" + error);
}
}
render() {
return (
<View style={styles.container}>
<Button
style={styles.formButton}
onPress={this.getKey.bind(this)}
title="Get Key"
color="#2196f3"
accessibilityLabel="Get Key"
/>
<Text >
Stored key is = {this.state.myKey}
</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
padding: 30,
flex: 1,
backgroundColor: '#F5FCFF',
},
});
I am able to get a key with onpress but i want without onpress. Please suggest.
Upvotes: 2
Views: 4578
Reputation: 2497
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 = await AsyncStorage.getItem('@MySuperStore:key');
this.setState({ myKey: value });
} catch (error) {
console.log("Error retrieving data" + error);
}
}
componentDidMount(){
this.getKey();
}
render() {
return (
<View style={styles.container}>
<Button
style={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.
Upvotes: 2