1 Replies - 492 Views - Last Post: 23 January 2022 - 02:28 PM

#1 Untalented   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 156
  • Joined: 31-January 12

How to prevent localStorage from overwritting stored localStorage data

Posted 22 January 2022 - 05:36 PM

Here is the code.. When I refresh the page and tried entering new data that i want to save, it overwrites the previous stored data
let form = document.getElementById('form');
let user = [];

form.addEventListener('submit', function (e) {
  e.preventDefault();
  let name = document.getElementById('name').value;
  let pw = document.getElementById('pw').value;

  let save = {
    "name": name,
    "pw" : pw
  }

  user.push(save);
  localStorage.setItem("user-list-test", JSON.stringify(user));

})



Is This A Good Question/Topic? 0
  • +

Replies To: How to prevent localStorage from overwritting stored localStorage data

#2 ArtificialSoldier   User is online

  • D.I.C Lover
  • member icon

Reputation: 3147
  • View blog
  • Posts: 8,965
  • Joined: 15-January 14

Re: How to prevent localStorage from overwritting stored localStorage data

Posted 23 January 2022 - 02:28 PM

You're always initializing user to be an empty array. You should only do that if there's nothing in localStorage, or else set it from that value.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1