How to Use Local Storage in JavaScript

At one point in your javascript journey, you'll need to store some data locally on the client's side. In this article, I’m going to explain what local storage is and how it works. And if this is your first time hearing the term “local storage”…you’re welcome.

There are different standards to store data in a user's web browser;

Cookies: Using Cookies was pretty much the only way data are stored in the browser until recently. It provides a maximum of 4kb of data storage, which means larger data can’t be stored all at once. Cookies are sent to the server for every request you make, and can be read on both client and server-side, but will be inaccessible to the client-side scripts if the cookie is marked as Http only.

Web SQL: Web SQL is similar to using relational databases and SQL, it involves storing data in a database and retrieving it using SQL. It has the capacity to store a larger amount of data, unlike cookies.

Session Storage and Local Storage: These are ways of storing data in JavaScript, and the only difference is that data stored in session storage gets cleared when the page is refreshed or when the browser is closed, but data stored in local storage persists. It doesn’t get cleared even after the page has been refreshed.

But today, we'll discuss local storage.

What is Local Storage?

Local storage is basically a way of storing information locally in the browser. It has the capacity to store up to 5mb of user data and also accessible from any browser or window. Another thing to note is, local storage is domain-specific, i.e. you only have access to the information you’ve saved when you are working with the domain that holds that data.

For example; if my website is mytodos.com, and I have stored todos like “read my book”, “do my assignment”, “go to the market” in that domain, I can only have access to these todos (data) when I visit mytodos.com.

How Do I Access My Local Storage?

Local storage can be accessed right from your web browser. First, you need to go to your developer tools by pressing F12, then go to the application tab, right there, you will find your local storage (F12 – application - storage – local storage – YourprojectPath ).

Picture1.png

Data can be stored based on named key/value pairs, you store your data with a key and retrieve your data with that same key. To use local storage in Js, there are methods you need to get familiar with; • setItem() • getItem( ) • remove( ) • clear( )

setItem( ) : This method is used to store key/value pairs to the local storage. The setItem method looks like the one we have below.

localStorage.setItem('name', 'Tomi');

‘name’ here is the key while ‘Tomi’ is the value. The main function of this ‘key’(‘name’) is to be able to fetch the value (‘Tomi’) attached to it later when you need it. To get back this value you have stored, you need to make use of the getItem( ) method.

getItem()

const user = localStorage.getItem('name');

//Tomi

As we can already see, getItem( ) can be used to get values already stored in the local storage by calling the key (‘name’) the value is attached to. Another point to note is that local storage has the ability to store only strings, this is because when objects or arrays are stored without converting to strings, and the values are checked in the console, it appears that these values are only stored as objects without displaying the real object information. Okay, that might be a bit confusing, let’s take a look at this;

const user = {
    Name: 'Tomi',
    Hobby: 'coding',
}
localStorage.setItem('users', user);
console.log(localStorage.getItem('users', user));

Now, when you check this in your console, you get something like this [object object]

Picture2.png

This isn’t so useful because the real object information you need is not included. To fix this, this object has to be converted first to a string using the JSON.stringify( ) method and converted back to an object using the JSON.parse( ) method.

const user = {
    Name: 'Tomi',
    Hobby: 'coding',
}
localStorage.setItem('users', JSON.stringify(user));
console.log(JSON.parse(localStorage.getItem('users', user)));

Now that the JSON.stringify() and JSON.parse() method has been applied, you get this in your console;

Picture3.png

JSON.stringify( ) here has successfully converted these objects into a string and we’re able to parse it back into the local storage using JSON.parse( ).

removeItem( ): Calling the removeItem( ) method removes the value of a given named key. Now, try to remove the value you got earlier,

localStorage.removeItem('users');

If you try to get this value back using getItem(), you get //Null as the result.

const user = localStorage.getItem('users');

 //Null

Clear( ): This method is used to clear or delete all the data already stored in local storage using local storage.clear( ) method. This can be a little tricky, for me, what I do is go to my editor, copy all my codes and keep them in a different file or better still, comment them out. I make sure everything is cleared, then I write localstorage.clear( ), save and reload my browser… and everything gets cleared. Now, you can go back to your editor and paste or comment out your code, save and refresh your browser and you’re good to go.

To make us understand these methods better, we are going to build a simple input page that saves users' names in the local storage even after the browser has been refreshed.

Let’s start with the HTML and CSS to speed things up;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Local storage</title>
</head>
<body>
    <label for="name">Your Name:</label>
    <input id="nameTag" type="text">
    <a href="#" class="save-btn">Save</a>

    <div class="display">
        <p></p>
    </div>

    <script src="./script.js"></script>
</body>
</html>

And our index.css looks like this, nothing serious, just some paddings and colors.

body{
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 200px;
}
.save-btn, .click-btn{
    color: white;
    background-color: rgba(0, 0, 255, 0.726);
    font-weight: bold;
    padding: 10px 10px;
    text-decoration: none;
    border-radius: 5px;
    margin: 0 5px;
}
input[type=text]{
padding: 10px 10px;
width: 30%;
}
.display{ font-weight: bold; background-color: pink;}

Moving to JavaScript, first, you define your variables.

const inputTag = document.getElementById('nameTag');
const saveButton = document.querySelector('.save-btn');
const Display = document.querySelector('.display');

Now that your variables have been defined, you can then make your button clickable by adding an EventListener.

saveButton.addEventListener('click', saveBtn);

Since your saveBtn hasn’t been defined, you have to use this function to execute your plan to make your button clickable and your input value visible on your browser.

function saveBtn(event){
    event.preventDefault();
    const displayName = document.createElement("p");
    displayName.classList.add('showName');
    displayName.innerText = inputTag.value;
    Display.appendChild(displayName);
}
saveBtn();

What we’ve successfully done here is that we created another element within our Html using createElement, we added a new class and then called our Html input value using inputTag.value and finally appended this value to the display div. Now that you are able to display your input value, the next step is to save this input value in your browser's local storage. To achieve this, the first thing to do is call the DOMContentLoaded event.

document.addEventListener('DOMContentLoaded', saveName);

This event runs when all the page’s DOM content has been loaded and parsed. Its target doesn’t include external resources like styles, images and so on, it sees the styles and images but doesn’t wait for them to completely load. So, the main function of this event listener in this lesson is to hold your local storage function, so it doesn’t get cleared even after the browser has been reloaded. Let’s move on to define our ‘saveName' function;

function saveName(){
    let results;
    if(localStorage.getItem('results') === null){
        results = [];
    }else{
    results = JSON.parse(localStorage.getItem("results"));
    }
    results.push(inputTag.value);
    localStorage.setItem("results", JSON.stringify(results));    
}

Basically, what this code does is, it checks first if you already have an array stored in the local storage, if you don’t, it creates an empty array ( results = [ ]; ), and if you already have an array, you parse back your array and push your values into this empty array. You then set it back to a string using the setItem( ) and JSON.stringify( ) method. For this code to run successfully, you have to call your saveName function inside the main function.

function saveBtn(event){
    event.preventDefault();
   …
 saveName();
}

By now, you should be seeing your arrays in the local storage, and you’ll also notice that your data doesn’t get cleared in the local storage if you refresh your browser.

Picture4.png

Yes, you have successfully stored your data in your local storage.

Local storage is not limited to what I’ve written above, but I hope it’s been able to give you the basic understanding you need to make use of your local storage. By now, you should be able to set an item to the local storage, get back your item, remove our item, and also get to clear all data present in the local storage.

Feel free to leave a comment or share if this post was helpful to you.

Onyedikachi E. Ibeabuchi's photo

I find this really helpful as I am currently learning Node. Thanks Rachel.

Rachel Tomi's photo

I'm glad to hear that Onyedikachi : )

Ezenwankwo Ugochukwu's photo

Very informative!