Adding user data to local storage only works once, thereafter the object being added is simply overwritten? (Angular 10+)

Viewed 26

I have a form which takes in user data. I am trying to write this inputted user data to my local storage. The first submit adds the record as expected, however, when trying to add a second record, the first records attributes are simply overwritten - do note, an array element is added, however its value is simply the id of the previous element.

This can be seen below:

After adding the first user (John), my local storage is as follows: enter image description here

After adding my second user (Alice), my local storage is now: enter image description here

I am using an interface, User:

export interface User {
  id : number;
  firstName : string;
  secondName : string;
  title : string;
  email : string;
  userRole : string;
  password : string;
}

The code for adding to the local storage is:

user = {} as User;

onSubmit() {
    console.log(this.addUserForm.value);
    this.user = Object.assign(this.user, this.addUserForm.value);
    this.addUser(this.user);
  }

  addUser(user: any) {
    var users = [];
    if (localStorage.getItem('Users')) {
      users = JSON.parse(localStorage.getItem('Users') || '{}');
      users = [user, ...Object.keys(users)]
    }
    else {
      users = [user]
    }
    localStorage.setItem('Users', JSON.stringify(users));
  }

Any reason as to why this may be happening?

1 Answers

...Object.keys(users) will only spread the keys of your array, which are 0, 1.., to the array.

You should just push the new user into the array like this:

users.push(user); // or users.unshift(user); if you want it to be the first element

or if you want to use the spread syntax:

users = [user, ...users]

instead of

users = [user, ...Object.keys(users)]
Related