Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add a value to localstorage, instead of replacing it

i want the value from newUsername to be added to the localStorage setUsernamesArray, whereas in my code, it replaces the entire value.

Code

$('#signUpButton').click(function() {
  var newUsername = $('#usernameSignInBox').val();
  signedUpUsernames.push(newUsername);
  localStorage.setItem('setUsernamesArray', signedUpUsernames);
});
like image 793
igetstuckalot Avatar asked Mar 13 '23 01:03

igetstuckalot


2 Answers

If you want to add to the array, you must realise that the value in localStorage isn't an array, it is a string. If you want that string to represent an array, and you want to update that array, you must do the following things:

  • read the string, localStorage.getItem('setUsernamesArray'),
  • then convert it to an array with JSON.parse,
  • then push to the array,
  • and then store it again with localStorage.setItem('setUsernamesArray', JSON.stringify(array))
like image 180
TKoL Avatar answered Mar 23 '23 19:03

TKoL


localStorage always store values as a string, so stringify your array and store,

localStorage.setItem('setUsernamesArray', JSON.stringify(signedUpUsernames));

And before reading it just parse it,

var arrayFrmStorage = JSON.parse(localStorage.getItem("setUsernamesArray"))
like image 37
Rajaprabhu Aravindasamy Avatar answered Mar 23 '23 19:03

Rajaprabhu Aravindasamy