React Native - Push new item(s) to existing AsyncStorage key?

Wonka picture Wonka · Aug 10, 2016 · Viewed 7.9k times · Source

I have a few scenarios where I need to store items in AsyncStorage and push new data to their respective keys. One of them is a list of 10 countries stored in AsyncStorage like this:

AsyncStorage.setItem('countries', JSON.stringify(countries));

I tried the following, where country is the new item I want to push/add to the pre-existing countries:

AsyncStorage.push('countries', JSON.stringify(country));

That didn't work of course...

As stated, I also have a few scenarios where this functionality is needed. I am trying to find a solution with a reusable react native AsyncStorage function to handle the the passed key and data, and take care of setting the item, or pushing to the item if it exists.

Any idea how to accomplish this functionality efficiently with AsyncStorage?

Answer

James111 picture James111 · Aug 10, 2016
var countries = AsyncStorage.getItem('countries');
AsyncStorage.setItem('countries', countries += JSON.stringify(country));

If you tried to grab the 'countries' data after concatting the two strings, you'd obviously get invalid json like so: {one json obj}{other json obj}.

You'd have to parse the JSON and then push it like so:

var countries = AsyncStorage.getItem('countries');
countries = JSON.parse(countries);
countries.push(country);

Once we've pushed the latest country we can then save the updated countries object to localstorage.

AsyncStorage.setItem('countries', JSON.stringify(countries));

Obviously you'd add try + catch blocks when grabbing and retrieving the local storage data (i've just left them out here).