LearnDeep95
LearnDeep95

Reputation: 53

How to store array in local storage angular?

I was trying to store data in an array to get it later in other component but it's provoking error:

ERROR TypeError: Cannot read property 'push' of undefined

I used local storage.

onSubmit() {
    let email = this.AuthForm.get("email").value;
    let password = this.AuthForm.get("password").value;
    let nomcomplet = "";
    let occupation = "";
    let niveau = 0;
    let newUser = new User(email, password, nomcomplet, occupation, niveau);
    console.log(newUser);
    let val: any = [];
    val = this.storage.get(this.key);
    val.push(newUser.email);
    this.storage.set(this.key, JSON.stringify(val));
}

I expected to find all the stored values in the local storage but the actual is error and only the last value get stored before

screen capture

enter image description here

Upvotes: 0

Views: 6134

Answers (2)

Wolf Blazer
Wolf Blazer

Reputation: 71

Ok let´s Try this

     let email = this.AuthForm.get("email").value;
     let password = this.AuthForm.get("password").value;
     let nomcomplet = "";
     let occupation = "";
     let niveau = 0;
     let newUser = new User(email, password, nomcomplet, occupation, niveau);
     console.log(newUser);
     let array: any = [];

     if (localStorage.getItem(keyToFindOrSave)) {
      //exist data on storage
      //so grab the storage
       array = JSON.parse(localStorage.getItem(this.key)); //we overwrite the same arry with the data from LocalStorage

    }

      console.log(array); //Watching if have some old data!
      array.push(newUser) //So we push the newUser , if exist something on localStorage the if before actually have the data
      console.log(array); //Watching with new data and old data
      localStorage.set(keyToFindOrSave, JSON.stringify(array)); //and save the data

Remember that keyToFindOrSave allways need to be the same (y)

And when you need the data on another component just grab with

let dataFromStorage : any;
if (localStorage.getItem(keyToFindOrSave)) { //always ask if exist the localStorage =D
 dataFromStorage = JSON.parse(localStorage.getgetItem(keyToFindOrSave));
}

Some Screenshot LocalStorage Data

Upvotes: 0

chrismclarke
chrismclarke

Reputation: 2105

You've stored your data as a string, so when you retrieve it you should parse it back to be an object.

set storage

this.storage.set(this.key, JSON.stringify(val));

retrieve from stroage

const storageVal = this.storage.get(this.key)
const val = JSON.parse(storageVal)

You may also want to add a method to handle cases where the storage object does not exist (returns a null value)

const storageVal = this.storage.get(this.key)
const val = storageVal ? JSON.parse(storageVal) : []

Upvotes: 3

Related Questions