How to write data to the webstorage without overwriting already recorded data?

Asked

Viewed 359 times

1

I created a form and when the user fills this form the data is sent to the local webstorage and from there to a table. However, whenever you write a data in localstorage the previous data is overwritten, is it possible to have the data sent to this table without replacing the existing data? Note: It has to be only with Jquery.

1 answer

2

As stated in other issues linked in the comments, you need to recover the existing data and add the new ones. Since web Storage accepts only strings, the recommended solution is to use JSON serialization to store objects, such as arrays, in string format and then retrieve the object by deserializing the string.

A specific solution for your case would be to create an object that encapsulates the necessary access.

As at this point I am interested in playing with JS, I made a simple solution that you could use as a base, without using libraries like jQuery.

The following object represents a row of submissions:

var submitQueue = (function() {
  var key = "my-form-queue";

  function fetchQueue() {
    var storedQueue = localStorage.getItem(key);
    console.log('Recuperando... ', storedQueue);
    return storedQueue === null ? [] : JSON.parse(storedQueue);
  }
  function saveQueue(queue) {
    var serializedQueue = JSON.stringify(queue);
    console.log('Armazenando... ', serializedQueue);
    localStorage.setItem(key, serializedQueue);
  }

  return {
    push: function(obj) {
      var queue = fetchQueue();
      queue.push(obj);
      saveQueue(queue);
    },
    take: function() {
      var queue = fetchQueue();
      var first = queue.shift();
      saveQueue(queue);
      return first;
    },
    peek: function() {
      return fetchQueue();
    }
  }
})();

It contains 3 methods:

  1. push: places an element at the end of the queue.
  2. take: removes the first element from the queue.
  3. peek: lets you recover a copy of the queue.

Example removing the first item from the queue:

var proximoItem = submitQueue.take();

Example adding an object to the queue:

var nome = document.querySelector('#nome').value;
var data = document.querySelector('#data').value;
if (nome && data) {
  submitQueue.push({ name: nome, date: data });
}

Example generating HTML code from a list of items:

var itensPendentes = submitQueue.peek();
var html = '<ol>';
itensPendentes.forEach(function(item) {
  html += '<li>Nome: ' + item.name + ', Data: ' +  item.date + '</li>';
});
html += + '</ol>';

For generation of a simple table, you can use similar code. In a real program, where tables usually need to be better finished, I suggest using a table component that accepts an object array as a data source.

Demonstration at Jsfiddle

Browser other questions tagged

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