Storage returning an array of array, instead of just array?

I am having this problem with storage. I want to store an array of objects. Before storing the array I stringify it and after I retrieve it I use JSON.parse to get the data. However, I keep retrieving an array of array and the first element is the array I need. Is it possible to just one not nested array?

I am sure I am doing something wrong. Here are the functions:

  storeRecords(key, records){
    let toStore;

    try {
      toStore = JSON.stringify(records);
    } catch (ex) {
      console.log(ex);
    }

    this.storage.set(key, toStore).then(records => {
       console.log("Added " + key + " : ", toStore);
    })
  }

  retrieveRecords(key) {
    let records = [];
    return this.storage.get(key).then(data => {
      try {
        records = JSON.parse(data);
        console.log("retireved from st: ", records);
      } catch (ex) {
        console.log(ex);
      }
        console.log("Retrieved " + key + " : ", records);
        return records;
    });
  }

Also, what is the most efficient way of storing something with ionic? I know there are different options.

Is there a reason you’re futzing around converting things to strings? I believe ionic-storage handles all that for you if you just give it an object.

Not really, I just played with it around and many other blogs do that as well (but perhaps thats for older version of ionic).

I tried this approach as well and still getting the same.

Here is how I call my function:

Promise.all([this.storageProvider.retrieveRecords('painRecords')]).then((data) => {
  console.log("RECORDS: ",data); 
})

Data here is an array of arrays.: from the log:
Array (1)
0 Array (1)
0 {date: “2017-01-22T00:28:48.643Z”, painScore: 3, kindOf …

Then the extra array is an artifact of the fact that you’re using Promise.all, I suspect.

is there a way to achieve the same as what I am doing without Promise.all ?

That depends on whether you are actually retrieving a bunch of other things (not just these pain records), and need them all at once. In the example you give here, you are just retrieving the pain records, so Promise.all is superfluous:

this.storageProvider.retrieveRecords('painRecords').then((painrecs) => {
  // painrecs should be just the object you stored
});

If you have oversimplified the example,

Promise.all([this.sp.retrieve('pain'), this.sp.retrieve('drugs'), this.sp.retrieve('notes')]).then((recs) => {
  let painRecs = recs[0];
  let drugRecs = recs[1];
  let notes = recs[2];
});
2 Likes

I see, I wil go ahead and do that! Many thanks!

But now I am having problems with retrieving nulls. Is there are any good ways of handling that? on the web many examples are only for ionic 1.

I receive null if such thing is not stored in storage.

I just compared with null and it worked!