achu
achu

Reputation: 797

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.

Upvotes: 29

Views: 100222

Answers (8)

Deepak Singh
Deepak Singh

Reputation: 1145

if you want to remove the selected list :-

 let key =[
    'visitorId',
    'visitorMobile',
    'visitorData',
  ]

await AsyncStorage.multiRemove(key)

Upvotes: 0

Omar bakhsh
Omar bakhsh

Reputation: 1054

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;
        }

    }

Upvotes: 0

Codemaker2015
Codemaker2015

Reputation: 1

Use removeItem() method to remove values from AsyncStorage in react.

try {
    await AsyncStorage.removeItem(key);
    console.log('Data removed')
}
catch(exception) {
    console.log(exception)
}

Upvotes: 2

Himanshu Dwivedi
Himanshu Dwivedi

Reputation: 8174

Try this:

async removeItemValue(key) {
    try {
        await AsyncStorage.removeItem(key);
        return true;
    }
    catch(exception) {
        return false;
    }
}

Upvotes: 91

Gautam Prajapati
Gautam Prajapati

Reputation: 56

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>

Upvotes: 1

404notBrighton
404notBrighton

Reputation: 170

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)
    }
};

Upvotes: 6

dhorelik
dhorelik

Reputation: 1507

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.

Upvotes: 3

ShaneG
ShaneG

Reputation: 1518

This is the framework code for AsyncStorage.removeItem:

removeItem: function(
 key: string,
 callback?: ?(error: ?Error) => void
): Promise {
 return new Promise((resolve, reject) => {
  RCTAsyncStorage.multiRemove([key], function(errors) {
    var errs = convertErrors(errors);
    callback && callback(errs && errs[0]);
    if (errs) {
      reject(errs[0]);
    } else {
      resolve(null);
    }
  });
 });
}

As you can see above it requires the key(Which is name of the item you set in asyncstorage that you want to delete) and a callback function. Make sure you have the correct key and the correct params and it should work fine.

Upvotes: 0

Related Questions