angularlocal-storageweb-storage

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


Solution

  • 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) : []