Push array in localstorage ERROR Error: Uncaught (in promise): TypeError: _this.items.push is not a function

savesociet()
{
if(this.email!="" && this.namesociet!="" && this.tele!="")
{

  this.storage.get(this.codekey)
    .then((result:any)=>{
      if (result) 
      {
         this.items=result;
        this.items.push({name:this.namesociet,email:this.email,tel:this.tele});
        this.storage.set(this.codekey, this.items);
      } else {
         this.storage.set(this.codekey,{name:this.namesociet,email:this.email,tel:this.tele});
      }
    
  })
  this.navCtrl.push('SocietsPage')

}else{
this.presentToast(‘s’il vous plaît sélectionner les deux champs’)
}

}

It’s best to format your code using the little </> button in the post editor.

Where is items defined?

inside the page

items:any = [];

What is result?

Based on the error I’m guessing that it’s not returning an array.

the result it is an array when i save the data from local storage

i have the data in my local storage and i want to push the new data to my existing local storage

After looking at it again it won’t be an array.

} else {
  this.storage.set(this.codekey,{name:this.namesociet,email:this.email,tel:this.tele});
}

The first time this function is called it’ll store an object rather than array.
What you want to do is save it as an array:

this.storage.set(this.codekey, [{name:this.namesociet,email:this.email,tel:this.tele}]);

its work thank you so much

You can simplify your code by re-arranging things as such:

    this.storage.get(this.codekey)
    .then((result:any[]) => {
      this.items = result || [];
      this.items.push({name:this.namesociet,email:this.email,tel:this.tele});
      this.storage.set(this.codekey, this.items);
    })
1 Like

okay thank you bro :+1:wink: