Shimanyi Valentino
Shimanyi Valentino

Reputation: 483

ionic Storage implemenation: get and set

I am trying to understand how to get and retrieve data from ionic Storage and I need some help since I am new at this.

Suppose I have line that sets the following JSON document into a storage key:

 person = [
     { "id": "0001", 1:"name", 2:"gender", 3: "age":"5"},
     { "id": "0002", 1:"name", 2:"gender", 3: "age":"5"}
    ]

using storage.set('persons', persons), I am able to set the values of the JSON to the persons key of ionic storage.

When I want to change the second item of the JSON file "id": 0002, should I read the whole JSON to memory, search for 0002 and modify then send back to a fresh JSON document to ionic storage? or there is a better way?

Thanks in advance.

Upvotes: 0

Views: 202

Answers (2)

Sergey Rudenko
Sergey Rudenko

Reputation: 9227

Ionic Storage is based on localForage library and it is a simple key/value storage.

Based on your example you have 2 options with this Storage:

  1. If overall size of person(s) object is relatively small you can indeed store whole object as one value. This means if you need to change an item inside object (or array) - you have to get full object (containing all persons data), change the item, persist (set) it again as a whole object

  2. If you expect to do a lot of these operations and size of data will grow you can approach this by “splitting” your object and using differentiated keys for each “person” item as value:

storage.set(“persons_person00”, persons[0])

This approach requires you to think carefully about your keys naming conventions as you will want to be very consistent with names.

Also in the latter approach you may need to use .forEach method of Storage depending on your needs to “read all” during initialization etc

Upvotes: 1

Seven
Seven

Reputation: 1

In my opinion, the best way is scroll through the array, change the specific item and then set the new obj with this change.

Upvotes: 0

Related Questions