Reputation: 1266
I have been trying to save input data on async storage but whenever i go back after input, it shows the previous data, not the updated one. Here's the code where i think some changes are needed.
constructor(props) {
super(props)
this.state = {
userData: {
address: ''
}
}
}
saveAddressEdit = (fieldName, fieldValue) => {
AsyncStorage.setItem(userData.address, fieldValue)
}
render() {
const {address} = this.state.userData
return (
<Input placeholder=" Type your Address:"
onChangeText={(address) => this.setState({address})}
value={address} />
<Button full danger onPress={()=>this.saveAddressEdit('address', address)} style={{backgroundColor:'#ff0000'}}>
);
}
Upvotes: 2
Views: 722
Reputation: 3773
If you want to persist you address through the component lifecycle using AsyncStorage then you should first save it properly and once you get back on the screen, fetch it and populate back it into your state, as component's state needs to be reinitialised using your AsyncStorage.
The following code should help initialize the address back to the stored one:
componentDidMount () {
AsyncStorage.getItem('address').then(value => {
if (value) {
this.setState({address: value});
}
})
}
and the below specifies the correct way to set the data to AsyncStorage:
saveAddressEdit = async (fieldName, fieldValue) => {
await AsyncStorage.setItem(fieldName, fieldValue)
}
OR you can also you the promise way just like I did in getItem
above like setItem(fieldName, fieldValue).then(value => console.log('saved'))
but since we don't need to handle anything in the then
so I resist using promise in such places.
Upvotes: 1