How to save array of data in native-storage

I am trying to make offline mode which saves data from API to native-storage but the issue is I cannot get them in array instead every time I save one it replaces with old one.

So the question is how do I save my data as an array in native-storage?

Code

View
This simply send my post url to server and return all data of that post in order to save them.

<ion-button (click)="addFavorite(post.url)">
  <ion-icon slot="icon-only" name="download"></ion-icon>
</ion-button>

posts.page.ts This function is supposed to store the returned data in an array.


item: any[] = [];


addFavorite(url: string) {
    return this.postsService.getDetails(url).subscribe(res => {
      this.storage.setItem('item', res)
        .then(
          () => {
            console.log('Item Stored');
          },
          error => console.error('Error storing item', error)
        );
      this.item.push(res);
      return res;
    });
  }

any idea?

yes, your code will definitely replace all data of key item in storage because you store value of res directly.
if you want to push res in current item data then first you have to fetch data from storage then push res into fetched item data variable and set into storage again.

1 Like

hi @hirenkorat3 thanks for responding,

would you mind show me how to? Iā€™m completely newbie with this and have no idea how should i do it!?

Thanks.

use sqlite database, if you want to store data offline.

Hi
hope this helps


item: any[] = [];

/*
* Fetches code from storage and assigns it to variables if any
*/
this.storage.get('item').then((res) => {
        if(res){
          this.item = res;
       }
});


addFavorite(url: string) {
    return this.postsService.getDetails(url).subscribe(res => {
     this.item.push(res);
      // Saving item array instead of res value.
      this.storage.set('item',  this.item)
        .then(
          () => {
            console.log('Item Stored');
          },
          error => console.error('Error storing item', error)
        );
   
      return res;
    });
  }
2 Likes

@krishna2112

Hi, thanks man I am trying this and during typing this code i get warnings

I prefer to use internal storage and not make my app size bigger than it is already, plus except this matter i have nothing more to save for using database.

Unless you can share with me some bright benefits of using database rather than native-storage i think native-storage is enough solution for my need.

Kind regards.

please add below code inside constructor


constructor()
this.storage.get('item').then((res) => {
        if(res){
          this.item = res;
       }
});
}


1 Like

nice one dude, working just fine :heart:

thank you

1 Like