Clearing App Data with React Native and AsyncStorage.

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Justin Ross

Justin Ross

Software Engineer and Dog Evangelist.