Clearing App Data with React Native and AsyncStorage.

Justin Ross
Drover Publications
2 min readNov 4, 2019

--

If you have been using React Native for any length of time, you’re likely familiar with AsyncStorage. This is the React Native equivalent of the browser’s LocalStorage, with the main difference being that it is asynchronous. If you’re unfamiliar with AsyncStorage, check out the documentation here. The docs are well written and include examples for most use cases.

What do the docs say?

One thing the documentation doesn’t fully cover is how to allow our users to clear their application data. The astute will have noticed a clear method is provided with the library but includes a warning that using this method will delete AsyncStorage data beyond the scope of our app.

Clear

Removes whole AsyncStorage data, for all clients, libraries, etc. You probably want to use removeItem or multiRemove to clear only your App's keys.

How do we clear app data only related to our app?

The task is quite simple. We can use getAllKeys to retrieve all storage keys related to our application and multiRemove to target just those keys.

const clearAppData = async function() {
try {
const keys = await AsyncStorage.getAllKeys();
await AsyncStorage.multiRemove(keys);
} catch (error) {
console.error('Error clearing app data.');
}
}

How does it work?

To understand how our approach works, it’s helpful to understand how AsyncStorage stores and retrieves your data under the hood.

Internally to AsyncStorage, all keys you provide are prepended with a unique identifier to reference your application. Consider the following:

await AsyncStorage.setItem('FavoriteColor', 'green');
await AsyncStorage.setItem('FavoriteFood', 'Lucky Charms');

Though we have used keys FavoriteColor and FavoriteFood here, the actual reference values internally used will be OurSpecialAppId_FavoriteColor and OurSpecialAppId_FavoriteFood. Internally, the getAllKeys method searches AsyncStorage for only keys prefixed with OurSpecialAppId_ to help it segment storage needs between apps.

Conclusion

Allowing our users to clear their application data is quick and easy. We just use getAllKeys to retrieve all storage keys related to our application and multiRemove to target those keys specifically.

--

--