Local Storage - Always replaces last data

Asked

Viewed 347 times

2

I have this code:

var ClienteArray = [];

$('#btn-save').click(function(){    
    var cliente = JSON.stringify({
        Code : $('#stn-code').attr('value'),
        Name   : $('#stn-name').attr('value')
    });     
    ClienteArray.push(cliente);
    localStorage.setItem('ClienteArray', JSON.stringify(ClienteArray));
    alert('Registro adicionado.');
    return true;

});

    $("#test").html(localStorage.getItem('ClienteArray'));

It takes the data placed in an input and passes to the localStorage in Json an array of data. But every time I click the save button, instead of putting a new data in the array it erases the old one and makes a new array, but I need it not to delete the old one. Does anyone have any idea?

2 answers

5


I assume it would be enough to load the array before updating it:

var ClienteArray = JSON.parse(localStorage.getItem('ClienteArray') || '[]');

$('#btn-save').click(function(){    
    var cliente = JSON.stringify({
        Code : $('#stn-code').attr('value'),
        Name   : $('#stn-name').attr('value')
    });     
    ClienteArray.push(cliente);
    localStorage.setItem('ClienteArray', JSON.stringify(ClienteArray));
    alert('Registro adicionado.');
    return true;

});

    $("#test").html(localStorage.getItem('ClienteArray'));

Note: has not been tested.

  • That’s right @Haroldo_ok !!! Thank you very much!

  • Okay, arrange.

2

Wagner, I know your case is much simpler, but if you need to, you can use the Storage.js, it serves as an abstraction for various storage technologies, such as the IndexedDB, WebSQL and Storage (whether Local or Session)

but note, now you are not working with a simple array, but with entidades which are stored in a scheme very similar to a banco de dados, then it is of interest that you report a id for each record.

then you can use the method getAll to list all their records and the set to make a upsert.:

storage(function (storage) {
  storage.getAll("Pessoa", function (pessoas) {
    console.log("consulta realizada com sucesso");
  });
}, "LocalStorage");

storage(function (storage) {
  storage.set("Pessoa", pessoa, function () {
    console.log("pessoa inserida com sucesso");
  });
}, "LocalStorage");

follows the full example, but the same does not work in sandbox, but you can check the same on JSFiddle

faker.locale = "pt_BR";
var gerarPessoa = function () {
  var pessoa = {};
  pessoa.id = newGuid();
  pessoa.Nome = faker.name.firstName();
  pessoa.Sobrenome = faker.name.lastName();
  pessoa.Nascimento = faker.date.past(50, new Date(1990, 1, 1));
  pessoa.Telefone = faker.phone.phoneNumber();
  pessoa.Email = faker.internet.email(pessoa.Nome, pessoa.Sobrenome);
  return pessoa;
}

var newGuid = function() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}

var appendPessoa = function(pessoa) {
  if (typeof pessoa.Nascimento == "string")
    pessoa.Nascimento = new Date(pessoa.Nascimento);
  var linha = document.importNode(tmplPessoa, true);
  linha.querySelector("td:nth-child(1)").textContent = pessoa.Nome;
  linha.querySelector("td:nth-child(2)").textContent = pessoa.Sobrenome;
  linha.querySelector("td:nth-child(3)").textContent = pessoa.Nascimento.toLocaleDateString();
  linha.querySelector("td:nth-child(4)").textContent = pessoa.Telefone;
  linha.querySelector("td:nth-child(5)").textContent = pessoa.Email;
  pessoas.appendChild(linha);
}

var gerar = document.getElementById("gerar");
var tmplPessoa = document.getElementById("tmplPessoa").content;
var pessoas = document.querySelector("#pessoas tbody");
var database = null;

storage(function (storage) {
  database = storage;
  database.getAll("Pessoa", function (pessoas) {
    pessoas.forEach(appendPessoa);
  });
}, "LocalStorage");

gerar.addEventListener("click", function () {
  var pessoa = gerarPessoa();
  database.set("Pessoa", pessoa, function () {
    console.log();
  });
  appendPessoa(pessoa);
});
table {
  width: 100%;
}
<script src="https://cdn.rawgit.com/Marak/faker.js/master/build/build/faker.js"></script>
<script src="https://cdn.rawgit.com/lcavadas/Storage.js/master/build/storage.js"></script>

<input id="gerar" type="button" value="Gerar Pessoa" />
<table id="pessoas">
  <thead>
    <tr>
      <th>Nome</th>
      <th>Sobrenome</th>
      <th>Nascimento</th>
      <th>Telefone</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

<template id="tmplPessoa">
  <tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</template>

  • Very interesting am post, I will give a studied on, thanks for the tip!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.