Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a list with React Native AsyncStorage: many keys or one?

I want to store a list of items with AsyncStorage. The list will be updated over time.

Here is an example of a state the list can be in:

[
  { 
    name: "Alice", 
    email: "[email protected]"
  }, 
  {
    name: "Bob", 
    email: "[email protected]", 
    address: "30 Madison Ave., NY"
  }
]

Now, it seems that there are two options for storing this list:

  1. Store each contact under its own key
  2. Store the whole list under one key

There are advantages to either approach - what is preferred in React Native?

like image 778
sdgfsdh Avatar asked Apr 07 '16 08:04

sdgfsdh


2 Answers

I think this depends on how you plan to use, access, and update the data. There are several asyncstorage methods you can use to help make either case easier.

If you decide to go the many keys route, have a look at multiSet and multiGet, which allows you to retrieve several keys in a single function call. And getAllKeys will save you the trouble of "keep[ing] track of all the keys you created", solving both of the problems mentioned by Fredrick Motte.

For updating many keys in one call, check out multiMerge which is a really powerful method, similar to mergeItem but multiple keys at once.

So, you see you can really go either route. If you divide your data up into multiple keys, then you'll probably just want to spend some time getting familiar with the methods I mentioned above.

And David's suggestion to give Relm a look might have some value for you as well, again... depending on your need.

like image 87
Chris Geirman Avatar answered Sep 28 '22 08:09

Chris Geirman


For ease of use I'd store the list as a whole; since then you don't have to keep track of all the keys you created for each contact individually; and loading/saving them will be easier (just one function call instead of looping over all of your contacts).

But this is mostly a personal preference; there are no real constraints for any of the two methods.

like image 40
Frederick Motte Avatar answered Sep 28 '22 09:09

Frederick Motte