Storing Todos Locally
Topic Overview and Actualization
Hello, and welcome to our journey about todo lists! In this lesson, we delve into the world of Data Persistence and Local Storage. We're going to figure out how to store our todo items right on our own machine, specifically in the web browser. By the end of this lesson, you'll be well-equipped to store and retrieve data even after the browser is closed and reopened. This feature gives the user freedom from the fear of losing their data accidentally. It's as if we're creating our own mini-database right in our web browser. So, let's plow ahead and get on with this exciting journey!
Introduction to Local Storage
Local storage is a type of web storage that allows JavaScript websites and apps to store and access data right in the browser with no expiration time. It's like a small database that lives in your browser. Even after closing and reopening the browser, the data persists, giving us a form of data persistence.
Can you think of examples where this could prove useful? Imagine you're filling out a lengthy form and accidentally refresh the page. Without local storage, all the information you've filled out would be lost. But if the website cleverly stored this data in local storage as you were filling it out, it could conveniently recover it, recovering your data and saving you time. Local storage could make this clever recovery possible. Now let's see how we can use it to store our todo items.
localStorage Methods
First, let's look at the local storage toolbox. There are three primary methods that are of utmost importance in using local storage: setItem, getItem, and removeItem.
At its core, local storage is like a box with many compartments, and we store data in these compartments. But to fetch the data or remove it when it's no longer needed, we need some tools, right? That's what these methods essentially are — our tools to work with local storage.
-
setItemmethod: This is used to put data into local storage. It's like putting a thing into a compartment of our box. It requires two arguments: a key and a value. The key is the name of the compartment, and the value is the thing itself. Let's put something into our local storage:JavaScriptHere,
favoriteColoris the key, andBlueis the value. So, we've storedBlueinto a compartment namedfavoriteColor. -
getItemmethod: Once our data is in local storage, we need a way to retrieve it. That's whatgetItemdoes. The key is required as an argument to access the compartment, as shown below:JavaScriptHere, we are fetching data from the compartment named
favoriteColor. So,myFavoriteColorwill hold the valueBlue. -
removeItemmethod: Sometimes, we no longer need the data we put in local storage, so we need to remove it. This is done usingremoveItem.JavaScriptWe can see that
favoriteColoris removed from local storage. If you try to getfavoriteColornow, it will returnnullbecause it's not in local storage anymore.
