Reputation: 115
I'm trying to store some data in my App using AsyncStorage, but the thing is whenever I submit the data and then navigate to the second screen (where the data should be stored) it is empty.
Here is my code
SendOrder.js
import Settlement from './Settlement';
export default class SendOrder extends React.Component {
state = {
text: '',
storedValue: '',
}
onSave = async () => {
const { text } = this.state
try {
await AsyncStorage.setItem(key, text);
Alert.alert('Saved', 'Successful');
} catch (error) {
Alert.alert('Error', 'There was an error.')
}
}
onChange = (text) => {
this.setState({ text });
}
render() {
return (
<View>
<View>
<Text>- Noter -</Text>
</View>
<View>
<TextInput
onChangeText = {this.onChange}
value = { this.state.text }>
</TextInput>
</View>
<TouchableOpacity onPress = { this.onSave }>
<Text style = { styles.addButtonText }> + </Text>
</TouchableOpacity>
</View>
);
}
}
Settlement.js
import SendOrder from './SendOrder';
const key = '@MyApp:key';
export default class Settlement extends React.Component {
state = {
text: '',
storedValue: '',
}
componentWillMount() {
this.onLoad();
}
onLoad = async () => {
try {
const storedValue = await AsyncStorage.getItem(key);
} catch (error) {
Alert.alert('Error', 'There was an error.')
}
}
render() {
const { storedValue, text } = this.state;
return (
<View>
<Text>{storedValue}</Text>
<View>
<TouchableOpacity onPress = {this.onLoad}>
<Text>Load Data</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
Upvotes: 1
Views: 3981
Reputation: 1940
Change this line " await AsyncStorage.setItem(key, text); " to " await AsyncStorage.setItem('key', text); " The name of the key should be string so it should be in single quote.
and Change this line " const storedValue = await AsyncStorage.getItem(key); " to " const storedValue = await AsyncStorage.getItem('key'); " The name of the set key which is called should be string so it should be in single quote.
The keys you are setting is different and the key your are getting is different
Upvotes: 0
Reputation: 5023
You need to store the storedValue
into the state inside onLoad
, like
onLoad = async () => {
try {
const storedValue = await AsyncStorage.getItem(key);
this.setState({ storedValue });
} catch (error) {
Alert.alert('Error', 'There was an error.')
}
}
Hope this will help!
Upvotes: 1