Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 300
Wonka Avatar asked Dec 25 '22 02:12

Wonka


1 Answers

var countries = await 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 = await 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).

like image 118
James111 Avatar answered Dec 31 '22 02:12

James111