Local Storage - Always replaces the last data

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 it to the localStorage in Json an array of data. But every time I click the save button, instead of putting a new die in the array it deletes the old one and makes a new array, but I need it to not delete that old one. Does anyone have any ideas?

    
asked by anonymous 20.10.2016 / 14:00

2 answers

5

I assume you just have 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: it has not been tested.

    
20.10.2016 / 14:05
2

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

But note, you are now not working with a simple array , but with entidades that are stored in a schema similar to a banco de dados , so it is interesting to report a id for each record.

then you can use the getAll method to list all your records and 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");

It follows the complete example, but it does not work in sandbox , however you can check it in 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><scriptsrc="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>
    
20.10.2016 / 15:35