J P
J P

Reputation: 422

Save and update array to local storage JS

I am trying to send an array to local storage, when i click on the button and input has a value, element is sended to the array in local storage like this:

["info before reloading 1","info before reloading 2","info before reloading 3"]

if I reload the page and write something in the input, all elements in array are deleted, and a new array is created with the new info i am typing like this

["new info 1","new info 2","new info 3"]

how could I do avoid initial info to be deleted , and the array just update and save in local storage like this

 ["info before reloading 1","info before reloading 2","info before reloading 3", "new info 1","new info 2","new info 3"];

Thanks for your help

var mydiv = document.querySelectorAll(".div_btn");
console.log(mydiv);

for(i=0; i<mydiv.length; i++){
   mydiv[i].addEventListener("click", function(){
      var parent = this.parentElement;
      console.log(parent.firstElementChild.innerHTML);
   });
}


var btn_local = document.getElementById("btn_local");
var user_name = document.getElementById("user_name");

var mi_array = []; 

btn_local.addEventListener("click", function(){
  var name_value =  user_name.value;
  if(name_value !== ""){

   mi_array.push(name_value);
   console.log(mi_array);

   var json_transform = JSON.stringify(mi_array);
   localStorage.setItem("usuarios", json_transform);
  }
})
 <input type="text" id="user_name" placeholder="ingrese su nombre">
    <button id="btn_local">Send array to local host</button>

Upvotes: 1

Views: 578

Answers (1)

Sohail Ashraf
Sohail Ashraf

Reputation: 10604

You have to get the localStorage data with localStorage.getItem first when saving the data to the localStorage.

if data exists then add the data to mi_array, otherwise keep the array empty.

In current code, you are ignoring the old data and replacing the array only with the new data

Try this.

var mydiv = document.querySelectorAll(".div_btn");
console.log(mydiv);
for (i = 0; i < mydiv.length; i++) {
    mydiv[i].addEventListener("click", function () {
        var parent = this.parentElement;
        console.log(parent.firstElementChild.innerHTML);
    });
}

var btn_local = document.getElementById("btn_local");
var user_name = document.getElementById("user_name");
var mi_array = [];
btn_local.addEventListener("click", function () {
    var name_value = user_name.value;
    if (name_value !== "") {
        // Get the data from localStorage
        let currentData = localStorage.getItem("usuarios");
        // Check the data if its not null
        mi_array = currentData ? JSON.parse(currentData) : [];
        mi_array.push(name_value);
        var json_transform = JSON.stringify(mi_array);
        localStorage.setItem("usuarios", json_transform);
    }
})

Upvotes: 2

Related Questions