I am putting together a check box that will push data to async storage in react native but am having trouble getting the data to stick. I've set up the function presumably to push data to storage when the box is checked and then when it is unchecked. Below is the code, it seems unchecking the box won't stick. When I open the app again the box is still checked, what might I be doing wrong here? Assume that as of right now the local item stored is true
and I want to make it false when I uncheck. To confirm nothing is changing I have added a button to call data.
const STORAGE_KEY = '@save_enableauto'
state={
enableAuto:false
}
_storeData = async enableAuto => {
let x = enableAuto;
console.log('setting auto messages to: ', !x);
//send check box to state
this.setState({ enableAuto: !x });
try {
if(x) {
await AsyncStorage.setItem(STORAGE_KEY, 'true')
alert('Data successfully saved!')
} else {
await AsyncStorage.setItem(STORAGE_KEY, 'false')
}
} catch (e) {
console.log(e)
alert('Failed to save name.')
}
}
_retrieveData = async () => {
try {
const enableAuto = await AsyncStorage.getItem(STORAGE_KEY);
if (enableAuto !== null) {
// We have data!!
console.log('receiving from local storage: ',enableAuto);
this.setState({ enableAuto:eval(enableAuto) });
}
} catch (error) {
alert('failed to load previous settings.')
// Error retrieving data
}
};
componentDidMount() {
this._retrieveData()
}
....
<Button title={'call Data'} onPress={() => this._retrieveData()}/>
<CheckBox
value={this.state.enableAuto}
onValueChange={() => this._storeData(this.state.enableAuto)}
/>
update _storeData call to:
<CheckBox value={this.state.enableAuto}
onValueChange={() => this._storeData(!this.state.enableAuto)}
/>
and your function body to :
_storeData = async enableAuto => {
let x = enableAuto;
console.log('setting auto messages to: ', x);
//send check box to state
this.setState({ enableAuto: x });
...
}