localstorage values resetting after refresh

30,167

Solution 1

You have to rewrite your code like the below to make it working,

var users = JSON.parse(localStorage.getItem('usernames')) || [];
var valueChanger = 1;

alert(localStorage.getItem('usernames'));

function addValue() {
  users.push($('#textInput').val());
  localStorage.setItem('usernames', JSON.stringify(users));
  alert(localStorage.getItem('usernames'));
}

Since localStorage only stores string, we need to stringify the array before storing and Parse it before reading.

Solution 2

Everytime, when page refreshes you're first statement creates new array instead of using old one.

var newUser = localStorage.getItem('usernames') || "";
var valueChanger = 1;
var users = [newUser];

alert(localStorage.getItem('usernames'));

function addValue() {
  var newUser = $('#textInput').val();
  users.push(newUser);
  localStorage.setItem('usernames', users);
  alert(localStorage.getItem('usernames'));
}

Thanks & Cheers :)

Share:
30,167
igetstuckalot
Author by

igetstuckalot

Updated on February 27, 2020

Comments

  • igetstuckalot
    igetstuckalot about 4 years

    i want to have an array (converted also to a localStorage value) box where the value of '#textInput' is added to the localStorage each time, however after refreshing and entering a new value, the new value is not added to the localStorage, but replaces it. I believe this is because after refreshing the data from users[] is set to null, but dont know how to fix it

    var users = new Array();
    var valueChanger = 1;
    
    alert(localStorage.getItem('usernames'));
    
    function addValue() {
      var newUser = $('#textInput').val();
      users.push(newUser);
      localStorage.setItem('usernames', users);
      alert(localStorage.getItem('usernames'));
    }
    
  • JDB
    JDB about 8 years
    This is incorrect. You are pulling from localstorage as if a simple string was stored, but you are writing an array to localstorage. This won't actually work. Raja's answer correctly parses the localstorage value.