Guardar datos
Que tu programa recuerde cosas aunque cierren la pestaña. Es lo que guarda el récord de nuestros juegos.
Saving data
Making your program remember even after the tab is closed. It is what stores the high score in our games.
El navegador tiene un cajón donde puedes dejar cosas: se llama
localStorage. Lo que guardes ahí sigue estando mañana, aunque
cierren el computador.
Dos instrucciones: setItem para guardar y getItem para recuperar.
Cada dato se guarda con una clave, que es el nombre con el que lo pedirás
después.
The browser has a drawer where you can leave things: it is called
localStorage. Whatever you put there is still around tomorrow,
even after shutting the computer down.
Two instructions: setItem to save and getItem to retrieve. Each
value is stored under a key, the name you will ask for later.
La primera vez que alguien entra, el cajón está vacío. Pedir algo que no existe devuelve
null, que significa "acá no hay nada".
Por eso siempre se guarda con un valor por defecto. El símbolo
|| —el "o" que viste en decisiones— sirve justo para esto: usa lo guardado, o
si no hay nada, usa este otro.
Y ojo con algo importante: todo se guarda como texto. Un número hay que
convertirlo de vuelta con Number() al recuperarlo.
The first time someone visits, the drawer is empty. Asking for something that is not there
returns null, meaning "nothing here".
So you always retrieve with a default value. The || symbol —
the "or" from the decisions tutorial — is exactly for this: use what is stored, or if
nothing, use this instead.
And mind this: everything is stored as text. A number has to be converted
back with Number() when you read it.
Como solo se guarda texto, una lista o un objeto no se pueden meter directamente. Hay que convertirlos a texto primero.
Eso lo hace JSON.stringify al guardar, y JSON.parse al recuperar.
Piénsalos como empaquetar y desempaquetar.
Since only text can be stored, a list or object cannot go in directly. You have to convert them to text first.
JSON.stringify does that when saving, and JSON.parse when
reading. Think of them as packing and unpacking.
Fíjate en el || "[]": si no hay nada guardado,
JSON.parse recibiría null y daría error. Ese valor por defecto es
una lista vacía en formato texto.
Note the || "[]": with nothing stored,
JSON.parse would receive null and throw an error. That default is an
empty list in text form.
Una advertencia que conviene entender desde ahora: localStorage
no es seguro. Cualquiera que abra las herramientas del navegador puede verlo
y modificarlo en dos clics.
Sirve perfecto para récords, preferencias, el idioma elegido o un borrador. Nunca para contraseñas, datos de tarjetas ni nada que no quieras que el usuario cambie a mano.
Y ten presente: es por navegador y por dispositivo. Lo que guardes en el computador no aparece en el celular, y se borra si limpian los datos de navegación.
A warning worth understanding now: localStorage is not secure.
Anyone opening the browser tools can read and edit it in two clicks.
It is perfect for high scores, preferences, chosen language or a draft. Never for passwords, card details, or anything you do not want the user editing by hand.
Also note: it is per browser and per device. What you save on the computer does not appear on the phone, and it is wiped if they clear browsing data.
Guardar y recuperar con localStorage, usar valores por defecto para la primera
visita, convertir listas con JSON, y qué no meter ahí nunca.
Con esto cierras la parte de aplicaciones web. Lo que viene es la más entretenida: dibujar y animar en pantalla.
Saving and retrieving with localStorage, using defaults for the first visit,
converting lists with JSON, and what never to put in there.
That closes the web application part. What comes next is the most fun: drawing and animating on screen.