6

I'm testing my React-Native application and want to remove all items from AsyncStorage in order to test the app from the beginning. And I am a bit confused.

I read the official documentation and found multiRemove and clear functions, but I cannot understand how to clear all items of my application (clear as far as I understood clear the whole storage of all applications and I'm afraid to use it), and multiRemove delete only keys that I give it in parameters, but I want to clear all keys.

I suppose I can do it through getAllKeys keys-values and remove it one-by-one, but maybe there is a more clear way to do it? :)

thanks

P.S: I tried to to like this:

clearAllData() {
    AsyncStorage.multiRemove([]).then(() => alert('success'));
}

but it doesn't work...

MrSmile
  • 1,217
  • 2
  • 12
  • 20

4 Answers4

15

I suppose I can do it through getAllKeys keys-values and remove it one-by-one, but maybe there is a more clear way to do it? :)

You should do that, that's the only way to remove all keys from your app.

Here is a simple way of doing it:

clearAllData() {
    AsyncStorage.getAllKeys()
        .then(keys => AsyncStorage.multiRemove(keys))
        .then(() => alert('success'));
}
Vencovsky
  • 28,550
  • 17
  • 109
  • 176
3

When your app runs, it is assigned a unique ID. Each stored key is prefixed by the ID. Therefore, all YOUR app's keys can be identified.

Using AsyncStorage.clear does not use unique identifiers and will delete keys for all clients, apps, and libraries. This might be OK in development but probably undesirable in production.

Per @Bruno Soares, multiRemove is preferred. However, note that 'await' can only be used within an async function. Combining Bruno's answer with @Prawesh Panthi, the following function will delete keys that are only associated with your app without having to explicitly identify the keys.

removeAppKeys = async () => {
  let keys = []
  try {
    keys = await AsyncStorage.getAllKeys()
    console.log(`Keys: ${keys}`) // Just to see what's going on
    await AsyncStorage.multiRemove(keys)
  } catch(e) {
   console.log(e)
  }
  console.log('Done')
}
1
removeFew = async () => {
  const keys = ['@MyApp_USER_1', '@MyApp_USER_2']
  try {
    await AsyncStorage.multiRemove(keys)
  } catch(e) {
    // remove error
  }
  console.log('Done')
}
  • 4
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Jul 29 '20 at 14:04
1

Here a way of doing it, using async/await:

const keys = await AsyncStorage.getAllKeys()
await AsyncStorage.multiRemove(keys)
Bruno Soares
  • 281
  • 3
  • 8