Ricardo Castañeda
Ricardo Castañeda

Reputation: 5812

How to preserve data in array from Ionic - this.array.push is not a function

The array storedArr = [] is used to store data using storage, however, I receive the .push is not a function when I try to fill it with the storage get method:

storedArr = this.storage.get('stored') ? this.storage.get('stored').then((e) => {e}) : [];

The esencial part of my code is:

import { Storage } from '@ionic/storage';

export class MyPage {
    constructor(
        private storage: Storage) {
    }

    // storedArr = []; This works but resets the array

    storedArr = this.storage.get('stored') ? this.storage.get('stored').then((e) => {e}) : [];

    saveToStorage() {
        this.storedArr.push({ // .push is not a function
          title: 'blabla',
          body: 'more blabla'
        });

        this.storage.set('stored', this.storedArr);
    }
}

How should I write that part of the code?

Upvotes: 0

Views: 999

Answers (2)

Kagiso Marvin Molekwa
Kagiso Marvin Molekwa

Reputation: 979

The Ionic this.storage.get actually doesn't return any value other then a promise which then has to be "subscribed" to.

So storedArr = this.storage.get('stored') ? this.storage.get('stored').then((e) => {e}) : []; on success actually stores a promise inside storedArr then on fail it still returns a promise. Hence the error - because Promise.prototype does not contain the push method. So the ternary operator will evaluate to true and so [] will not be assigned to storedArr.

In order to get the value of the Ionic this.storage.get('stored') you have to "subscribe" to the returned promise and then assign the data parameter to storedArr. Like so...

export class MyPage {
  storedArr = [];

  constructor(private storage: Storage) {
      this.storage.get('stored')
          .then(data => {
            this.storedArr = data;
          });
  }

  saveToStorage() {
      this.storedArr.push({ // .push is not a function
        title: 'blabla',
        body: 'more blabla'
      });

      this.storage.set('stored', this.storedArr);
  }
}

Upvotes: 1

BRass
BRass

Reputation: 3838

If you're storing something other than a simple primitive value, you'll likely need to do a JSON.parse() on the storage getter result. Something like below. I adjusted to use await (in place of your thens), which I think is much clearer.

var storageResult = await this.storage.get('stored');
storedArr = (storageResult) ? JSON.parse(storageResult) : [];

Additionally, when you store the array you likely want to do a JSON.stringify on it.

this.storage.set('stored', JSON.stringify(this.storedArr));

Upvotes: 0

Related Questions