how to remove an item from AsyncStorage? right now I am trying this code
AsyncStorage.removeItem(\'userId\');
but this is not working for me.
This looks correct, but maybe you are trying to read back from AsyncStorage
too soon? It's asynchronous, so the change isn't applied right away and you might still see the key if you try to get it on the following line. Try to call AsyncStorage.removeItem
with await
or do what you want to do in the callback.
Try this:
async removeItemValue(key) {
try {
await AsyncStorage.removeItem(key);
return true;
}
catch(exception) {
return false;
}
}
Use removeItem()
method to remove values from AsyncStorage
in react.
try {
await AsyncStorage.removeItem(key);
console.log('Data removed')
}
catch(exception) {
console.log(exception)
}
This is what I did, had a similar issue.It works well when you want to remove an item based on its id. make sure each item has a unique id.
remove_user = async(userid) => {
try{
let usersJSON= await AsyncStorage.getItem('users');
let usersArray = JSON.parse(usersJSON);
alteredUsers = usersArray.filter(function(e){
return e.id !== userid.id
})
AsyncStorage.setItem('users', JSON.stringify(alteredUsers));
this.setState({
users:alteredUsers
})
}
catch(error){
console.log(error)
}
};
try this for react-native
const deletCar = async () => {
try {
await AsyncStorage.removeItem('@storage_Key').then(() => {
// props.navigation.navigate('same page name refresh ');
/* setprevCar({ carNumner: '', carModel: '' }) return empty obj if deleted. */
})
}
catch (exception) {
return false;
}
}
this delete method which removes object from array by passing index (here i called id)
async deleteData(id) {
try {
this.state.item.splice(id, 1);
await AsyncStorage.setItem("mylist",JSON.stringify(this.state.item))
this.setState({ item: JSON.parse(await AsyncStorage.getItem("mylist")) })
} catch (error) {
console.log(error);
}
};
and call this by using onPress method, here i am using button and pass index
<Button onPress={this.deleteData.bind(this,index)}>delete</Button>