Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an item from AsyncStorage in react-native

How to remove an item from AsyncStorage? right now I am trying this code:

AsyncStorage.removeItem('userId');

but this is not working for me.

like image 506
achu Avatar asked Nov 30 '17 11:11

achu


People also ask

How do you store objects in AsyncStorage in React Native?

AsyncStorage only accepts and stores string data, so in order to store object data or value we need to use JSON. stringify() method while saving the data and JSON. parse() method is for parsing objects that were received as JSON string.

How check AsyncStorage React Native?

To see what's stored in AsyncStorage with React Native, we can use the getAllKeys and multiGet methods. to call setItem with 3 key-value entries. Then we call getAllKeys to return all entries for all the keys. Next, we call multiGet with keys to return an array with the entries with the given keys .

How much data can be store in AsyncStorage in React Native?

Note that on Android AsyncStorage has an upper size limit of 6MB.


2 Answers

Try this:

async removeItemValue(key) {
    try {
        await AsyncStorage.removeItem(key);
        return true;
    }
    catch(exception) {
        return false;
    }
}
like image 167
Himanshu Dwivedi Avatar answered Oct 15 '22 10:10

Himanshu Dwivedi


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)
    }
};
like image 35
404notBrighton Avatar answered Oct 15 '22 11:10

404notBrighton