Saving data in localStorage

May 18, 2020 • edited May 19, 2020

Along with the arrival of HTML5 we have seen many improvements in the way how to save data in the user’s browser, such as localStorage and sessionStorage , the latter coming to replace the obsolete cookies.

Both cookies, sessionStorage and localStorage have limitations on the length of data that we can have. Thus, cookies only allow up to 4095 bytes to be saved, while sessionStorage and localStorage support between 8MB and 10MB depending on the browser (just the true beauty of these), so that we can transfer data between pages temporarily while the user browses our site (sessionStorage) or we can leave locally saved data indefinitely -or until the user cleans their browser- (localStorage).

Now, let’s focus on the data saved indefinitely. For this effect we could use Web SQL or Indexed Database , but it would be too much if we only need basic data such as name, surname, nationality or others, so we will use localStorage.

Let’s know the methods to handle the data with localStorage

To save the data we have two alternatives:

localStorage.setItem('nombre_storage','Mi data guardada');
localStorage.nombre_storage = 'Mi data guardada';

To read our storage the theme is similar to the previous one:

console.log(localStorage.getItem('nombre_storage')); // RESPUESTA: 'Mi data guardada'
console.log(localStorage.nombre_storage); // RESPUESTA: 'Mi data guardada'

To delete the storage in question:

localStorage.removeItem('nombre_storage');

To know the number of storages saved in our browser (all of them, including those created by other websites):

console.log(localStorage.length);

To delete all storages (including those created by other websites):

localStorage.clear();

Now let’s go to the best thing about localStorage: saving objects. As part of the DOM, localStorage is an object, but unfortunately it doesn’t allow saving them directly, so we must convert this data to a string.

Let’s assume we have the following object:

var dat = {
    nombre: 'Junior',
    apellido: 'Hernandez',
    edad: '[inmencionable]',
    nacionalidad: 'Dominicano',
    residencia: 'Santo Domingo'
};

We convert the data to a text string using JSON.stringify:

var datStr = JSON.stringify(dat);
localStorage.setItem('junidata',datStr);

Then, we parse the string with JSON.parseto return it as a javascript object:

var datObj = JSON.parse(localStorage.junidata);
console.log(datObj.nacionalidad); // RESPUESTA: Dominicano

Done, from now on we can save all the user’s data as an object and consult it from the same browser, safeguarding resources from our servers. Of course, it is important to note that sensitive user data cannot be left lightly without being encrypted, so be very careful with that detail. ;-)

JavaScript

Junihh

Junihh is talk about web-dev and opinion.

New scheme for a more semantic web

Search in a text string with 'in'