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:
- Dexies.js: Minimalist abstraction of IndexedDB.
- LocalForage: Key-value database.
- ZangoDB: MongoDB-like NoSQL database.
- pouchdb: CouchDB-like NoSQL database.
- lovefield: Relational database.
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.
Building SPAs with Django and HTML Over the Wire: Learn to build real-time single page applications with Python
The HTML over WebSockets approach simplifies single-page application (SPA) development and lets you bypass learning a JavaScript rendering framework such as React, Vue, or Angular, moving the logic to Python. This web application development book provides you with all the Django tools you need to simplify your developments with real-time results.
Buy the bookHelp me keep writing
Every coffee gives me a push toward the next article.
Sure, it's on me!
Comments
There are no comments yet.