10. Storage

When you refresh or leave a page, the information that was in the variables disappears. Everything starts over like Groundhog Day. The data used in variables evaporates without a trace, showing no mercy. Unless we rely on a backend, which in turn is connected to a database. Or at least that's how it has traditionally been. Fortunately tools evolve, and in the frontend quite intensely. We can save information in the user's browser, and retrieve it whenever we need it. Even structured as if it were a relational or NoSQL database.

dataset

It gives us the ability to save information, without breaking the standard, in HTML elements. Very useful when you want to communicate HTML with JavaScript or give certain configuration parameters to Web designers.

To do this you can declare a key in the form of an attribute that must start with data-.

<article
  class="personaje-historico"
  data-nombre="Charles Darwin"
  data-campos="historia natural y geología"
  data-anyo-de-muerte="1882"
>
...
</article>

To use them from the Front we'll use dataset.

const miArticulo = document.querySelector('.personaje-historico');

miArticle.dataset.nombre // "Charles Darwin"
miArticle.dataset.campos // "historia natural y geología"
miArticle.dataset.anyoDeMuerte // "1882"

What happened with anyo-de-muerte? The rule is simple: if you have spaces you must use Kebab case (soy-un-ejemplo) in HTML but Camel case in JavaScript (soyUnEjemplo). You can learn more in the following article.

This information is read-only, it cannot be modified unless it is generated from a backend.

localstorage

Allows you to save data in the browser that remains accessible indefinitely, even if the browser is closed, making it possible to retrieve it on subsequent visits (unless it's in an incognito or private tab). Its concept is similar to the old Cookies.

You shouldn't use Cookies when LocalStorage exists, since it modernizes and simplifies their use, and also increases the memory limit from Cookies' 4KB to LocalStorage's 5MB.

Save

const miLocalStorage = window.localStorage;
miLocalStorage.setItem('regalo', 'calcetines');

Save arrays or JSONs

We'll use JSON.strigify() to encode the information.

const miLocalStorage = window.localStorage;
miLocalStorage.setItem('regalo', JSON.stringify(['piruleta', 'tren', 'consola']));

Read

const miLocalStorage = window.localStorage;
const regalo = miLocalStorage.getItem('regalo');

console.log(regalo);
// 'calcetines'

If an array or JSON was stored.

const miLocalStorage = window.localStorage;
const regalo = JSON.parse(miLocalStorage.getItem('regalo'));

console.log(regalo);
// ['piruleta', 'tren', 'consola']

Delete an element

const miLocalStorage = window.localStorage;
localStorage.removeItem('regalo');

Delete everything

const miLocalStorage = window.localStorage;
localStorage.clear();

IndexedDB

Allows you to save large amounts of information in a structured and ordered format. It also lets us store files or blobs. Its concept is similar to having a database directly on the client side.

Since it's a low-level implementation, it's recommended to use a library to increase productivity, as they also incorporate abstractions that help with learning it.

Among the most recommendable we can find:

Activity 1

Design a square with a red background using the following HTML.

<div data-encendido="true"></div>

If data-encendido is true, its background will be red. If data-encendido is false, it will be black.

Extend it with data-enchufes.

<div data-encendido="true" data-enchufes="6"></div>

Generate x circles inside the tag depending on data-enchufes. A div using border-radius: 50% will be enough, though you can use images.

Activity 2

Create a Website where we can log our daily weight. You'll need 2 fields:

  • Weight of type float.
  • Date of type Date.

The requirements are that it must remember the data, every time we enter the previous content will be present.

Nightmare level 👹

  • It must calculate the average weight being lost.
  • Build a visually appealing chart.
Activity 3

Show a banner that can only be viewed on the first occasion. If we refresh, or come in again, it won't appear again.

This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.

Desafíos de programación atemporales y multiparadigmáticos

Desafíos de programación atemporales y multiparadigmáticos

Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.

Buy the book

Will you buy me a coffee?

This is how I keep writing without ads or paywalls.

Comments

There are no comments yet.