Storing arrays using local storage and getting value from it

I’m storing an array using the https://ionicframework.com/docs/storage/ but i’m having difficulty accessing that array when using it other parts of my code. I’m using this to fetch the value in storage

this.favouriteDrinkIds = this.storage.get(STORAGE_KEY)

Then trying to use that to do this to filter an array

this.filteredBeers = JSON.parse(JSON.stringify(this.items))
    this.filteredBeers = this.filteredBeers.filter((beer) => {

      return this.favouriteDrinkIds.indexOf(beer.drink_id) !== -1;


      });

But i get the following error

Uncaught (in promise): TypeError: _this.favouriteDrinkIds.indexOf is not a function TypeError: _this.favouriteDrinkIds.indexOf is no

Am i being stupid? Or what am i missing?

storage.get returns a Promise, so you can’t just do bla = this.storage.get('blah');

You’ll have to do something like this:

this.storage.get(STORAGE_KEY).then(ids => this.favouriteDrinkIds = ids);

And make sure the rest of your code waits for it to be loaded before using.

Ah i see, fairly new to this version of ionic so not quite sure what i’m doing wrong sometimes.

What’s the best way of delaying the rest of the code before it uses it?

Cheers

It’s a little hard to say, and my statement was more of a generic warning, as I’m not sure when you’re filtering.

Are you loading the data and then immediately filtering? Or are you loading the data on page load, and then waiting for user input?

I’m loading the data then immediately filtering before the data is then displayed, no waiting for user input.

Ah, good deal. I’d just move the filtering code inside the promise block then:

this.storage.get(STORAGE_KEY).then(ids => {
  this.favouriteDrinkIds = ids;
  this.filteredBeers = JSON.parse(JSON.stringify(this.items));
  this.filteredBeers = this.filteredBeers.filter((beer) => {
    return this.favouriteDrinkIds.indexOf(beer.drink_id) !== -1;
  });
});

Brilliant this has actually solved all my problems, i think some of my code was in the wrong places so some things couldn’t access other things but this appears to work now.

Thanks. Really Appreciate, think i’m sort of getting my head around it.