Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

localstorage values resetting after refresh

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'));
}
like image 576
igetstuckalot Avatar asked Feb 07 '23 15:02

igetstuckalot


2 Answers

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.

like image 91
Rajaprabhu Aravindasamy Avatar answered Feb 11 '23 00:02

Rajaprabhu Aravindasamy


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 :)

like image 28
Amulya Kashyap Avatar answered Feb 11 '23 00:02

Amulya Kashyap