Muhammad
Muhammad

Reputation: 349

Ionic 2 and JSON Data Addition

I am working with Ionic 2 Storage to persist form data. I save the data like this:

this.storage.set(key, JSON.stringify(formData));

And I retrieve and attempt to update the data like this:

this.getReport(key).then((report) => {
  var objReport = JSON.parse(report);
  objReport.push(data); //this is the problem
  this.storage.set(pk, JSON.stringify(objReport));
});

getReport is just this:

getReport(key) {
  return this.storage.get(key);
}

So I know that .push is for arrays and not objects, but I don't think its efficient to do all this conversions because I am dealing with large objects.

My question is: what is the most efficient way to retrieve json from storage and append to it? It makes no sense to me that .parse returns an object if objects do not have a push method like arrays.

Here is the error:

Runtime Error Uncaught (in promise): TypeError: Cannot read property 'push' of undefined TypeError: Cannot read property 'push' of undefined

Upvotes: 0

Views: 1352

Answers (1)

Bala Abhinav
Bala Abhinav

Reputation: 1348

what this error means is that, there are no records for that key at this moment. So, you would have to do a check like this :

this.getReport(key).then((report) => {
  var objReport = [];//initialise empty Array
  if(report){ //if there is a record in that key location
     objReport = JSON.parse(report); //parse the record & overwrite objReport
  }
  objReport.push(data); //Now this push will happen regardless of report or not
  this.storage.set(pk, JSON.stringify(objReport));
});

Upvotes: 1

Related Questions