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


#1

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’)
}

}


#2

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

Where is items defined?


#3

inside the page

items:any = [];


#4

What is result?

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


#5

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


#6

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


#7

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}]);

#9

its work thank you so much


#10

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);
    })

#11

okay thank you bro :+1:wink: