Saving in the Browser
Everything a page keeps in variables is gone when you reload it, because the script runs again from the start. For the data from the server, that's no problem: the page simply loads it again. But the user's own things, such as their settings or the films they've marked, aren't on the server. The page has to keep them somewhere else.
For that, the browser has localStorage, a small storage that each website gets in the browser. What a page saves there stays after a reload, and even after you close the browser. It's kept in this browser on this computer: other people don't see it, and neither does the same website in another browser.
You save a value under a name, called a key, and later read it by the same key:
localStorage.setItem("color", "green");
console.log(localStorage.getItem("color"));
console.log(localStorage.getItem("size"));
localStorage.removeItem("color");
console.log(localStorage.getItem("color"));green
null
nullsetItem(key, value)saves the value under the key. If something is already saved under it, the new value replaces it.getItem(key)returns what's saved under the key, ornullwhen nothing is. You knownullfromquerySelector(): it means “nothing”.removeItem(key)deletes the key with its value.
When the page opens, it reads what it saved before. getItem() may return null, so check that first:
const savedColor = localStorage.getItem("color");
if (savedColor !== null) {
colorText.textContent = `Your favorite color: ${savedColor}`;
}Without the check, a new visitor would see Your favorite color: null.
In the preview, each click on Run opens the page again, as a reload does, and the page finds what it saved in earlier runs while you have the exercise open. Once it has saved something, the console shows a Clear saved data button, which deletes it all, as if the page had never been opened. Resetting the code (the round arrow next to Run) deletes it too.
Instructions
When saveButton is clicked, save the city from cityInput in localStorage under the key city, and show Your city: London (with the city that was typed in) in cityText.
When the page opens, read the saved city. If there is one, show it in cityText in the same way. Try it: save a city and click Run. When nothing is saved, the page has to keep its text You haven't chosen a city yet.
When forgetButton is clicked, delete the saved city with removeItem() and show You haven't chosen a city yet. in cityText again.