How to use localStorage in javascript for absolute beginners!

How to use localStorage in javascript for absolute beginners!

Have you ever wanted to store your data somewhere when building web applications and access it easily without needing a backend developer? Well, localStorage gives you the opportunity to do that. It makes it easy for developers to store data, access it and also manipulate it.

What exactly is localStorage?

LocalStorage is a mechanism within Web Storage API. The web storage API provides mechanisms such as sessionStorage and localStorage in which users can store data in key/value pairs just like in objects. Local storage is a web storage type that allows developers to store and access data from the browser at any time. The data is stored for as long as its needed and even after the browser/tab is closed, the data will still be there for the developer to access. While in sessionStorage, the data is stored in sessions which means that the data is lost whenever the browser/tab is closed.

How does the localStorage work and when should you use it?

Local storage stores data in form of strings. So if you have arrays, objects, lists or any data type that isn't a string , you would have to convert it to a string using the JSON.stringify() method. Now, because you can store data in localStorage doesn't mean that you are advised to use it all the time. Local storage has a limit to the amount(size) of data it can save. It can only store up to 5mb of data which means if you are building web applications that are heavy and definitely has more than 5mb of data, it isn't advised to use localStorage. And also, localStorage should only be used when storing insensitive information because these information can be easily accessed by third party individuals.

Limitations of localStorage

Just like with all good things, there's always a catch. There are some limitations to using localStorage that I would really love to emphasize on!

  • localStorage should not be used to store sensitive information such as your passwords, credit card numbers, social security numbers and other sensitive information because they can be accessed easily. localStorage isn't secure!

  • localStorage saves the data in the browser. It does not have a database to store data so it isn't a substitue for server-based database.

  • localStorage is synchronous which means that each operation runs one after the other.

  • localStorage has limited space capacity.

Methods in localStorage

There are some methods that you would need to know in order to use localStorage effectively. I'll discuss the methods below and include some codes on how they work. localStorage is located at the Application section after you open developers tools or click inspect.

setItem()

This method is used to store an item to local storage. localStorage stores items in key and value pair.

// lets create a variable named myName that stores my name to localStorage
let myName = 'Omokaro Loveth';
// Now, we are going to save myName to localStorage
window.localStorage.setItem('savedMyName', myName)

This code saved the variable myName to the localStorage. The setItem syntax takes two parameters, a key and a value. The first parameter is the key which in this case is savedMyName while the second parameter is the value which is what we want to assign to the key and in this case it's myName.

UZgeydxwRu.png

The reason why this line of code worked is because the variable myName is a string. If it were other data type, we would have to convert it to a string before we can save it to localStorage. Let me show an example of such situation.

// Lets create an object and try saving it to localStorage
const obj = {
    myName : 'Loveth',
    height : 165
}
// lets try to save it to localStorage
window.localStorage.setItem('newObj', obj)
// After this code is run, an error is shown.

1PY0oJylSG.png

But if the object is converted to string before saving it to localStorage, it would work perfectly!

window.localStorage.setItem('newObj', JSON.stringify(obj))
// This would run perfectly and the object is saved to the localStorage

getItem()

So, let's imagine you have successfully managed to store an item in localStorage. Now is that the end? What is going to happen to that data that was stored? What if you want to access and manipulate it? Well, there is a method for you to retrieve or get the data / item that has been stored in localStorage and that method is the getItem method. The getItem() method allows you to be able to retrieve the data or item that has been stored to localStorage. It takes the key as the only parameter. Now let's try to retrieve our previously saved key which is savedMyName and console.log the result.


// we have to save the gotten item into a variable so we can console the answer
let retrievedName = window.localStorage.getItem('savedMyName')
console.log(retrievedName)
// This returns the string "Omokaro Loveth"

If we try to do the same thing for the object we previously saved to localStorage, we would get the object as a string because remember, we converted it to a string before we saved it to localStorage.

// we have to save the gotten item into a variable so we can console the answer
let retrievedObj = window.localStorage.getItem('newObj');
console.log(retrievedObj);
// This returns the object as a string. Lets check the data type
console.log(typeof(retrievedObj))

c6vzaV5zC4.png

At line 25, the data type there is a string. In order to retrieve the data as an object, we have to parse the data.

// we have to save the gotten item into a variable so we can console the answer
let retrievedObj = window.localStorage.getItem('newObj');
// now we have to parse the gotten item in order to convert it to its appropriate
// data type
retrievedObj = JSON.parse(retrievedObj)
console.log(retrievedObj);
// This returns an object. Lets check the data type
console.log(typeof(retrievedObj))

lrCQ691wdk.png

This returns an object and now, you can manipulate it.

removeItem()

The removeItem method is used to remove an item from localStorage. It takes a key as the only parameter.

// Remember we have saved two items to localStorage. Now we are going to remove 
//the item with the key savedMyName
window.localStorage.removeItem('savedMyName')
// This removes the item with the key name passed as the parameter.

3koWsh44O5.png

The savedMyName item that was saved to localStorage has been removed.

clear()

This method removes all the saved items from localStorage. It does not take any parameter.

// This will clear all the items/data saved to localStorage
window.localStorage.clear()

oMPyvIfbsc.png

The localStorage then becomes empty.

Project

Now that we have learnt how to use the different localStorage methods, let's try and create a little counter project that saves the number of count to localStorage and then displays the previously saved count after you refresh the page or reopen the tab/window.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/style.css">
    <title>Counter</title>
</head>
<body>
    <main>
        <section id="counter">
            <h2>Buy a hoodie for your babe😍😍</h2>
            <div class="img-container">
                <img src="img/hero-bg-2.jpg" alt="image of a girl wearing a sweater">
            </div>
            <p>The current pieces of hoodie is <span id="quantity-el">0</span></p>
            <p>The previous pieces of hoodies bought is <span id="prev-saved">0</span></p>
            <div class="counter-btn">
                <button type="button" id="decrease-btn">Decrease quantity</button>
                <button type="button" id="increase-btn">Increase quantity</button>
            </div>
            <div class="submit-div">
                <button type="button" id="save-btn">Buy</button>
            </div>
        </section>
    </main>

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

There are three buttons on the page. The increment button increases the count of the quantity of the hoodie that's going to be bought while the decrement button reduces it. The quantity-el span displays the quantity number. The buy button saves the current quantity number to the localStorage while the prev-saved span displays the saved quantity on page reload. Then the clear button clears the localStorage.

sFmOGC0fbC.png

const decrementEL = document.querySelector("#decrease-btn");
const incrementEL = document.querySelector("#increase-btn");
const quantityEl = document.querySelector("#quantity-el");

let count = 0;
// function to decrease the quamtity on clicking the decrease button
decrementEL.addEventListener("click", ()=>{
// decrease the count value with 1 whenever this button is clicked
    count -= 1;
// Display the value of count in the DOM
    quantityEl.textContent = count;
})

// function to increase the quantity on clicking the increase button
incrementEL.addEventListener("click", ()=>{
// increase the count value with 1 whenever this button is clicked
    count += 1;
// Display the value of count in the DOM
    quantityEl.textContent = count
})

When the increase quantity button is clicked, the value of the quantity of hoodies to be bought increases by 1. But when the decrease quantity button is clicked, the value of the quantity of hoodies increase by 1. Now lets implement the save function.

CpkIGIbv6M.png

// Save function that saves the value of count to localStorage
saveEL.addEventListener("click", ()=> {
// On click of the buy button, the value of the count is saved to localStorage
    window.localStorage.setItem("quantitySaved", count)
})

wNdlSgHKb2.png

Now, the next thing I would like to implement is that the value of the previously saved should change from 0 to the number saved on page reload.

// Displaying the previously saved quantity from the localStorage

window.onload = () => {
    // Assigning the value to a variable
    let displaySavedQuantity = window.localStorage.getItem("quantitySaved");
    // If there is no previously saved value to the localStorage, dislay 0
    // Else display the saved value
    if (displaySavedQuantity === null){
        prevSavedEl.innerHTML = 0;
    } else {
        prevSavedEl.innerHTML = displaySavedQuantity;
    }
}

Whenever the page is reloaded or opened and the buy button has already been clicked before, the value saved to localStorage would be displayed.

ddzGlM44Un.png

Now, lets implement the clear function that clears all the keys and values saved to the localStorage.

clearEL.addEventListener("click", ()=> {
    window.localStorage.clear()
})

When the clear button is clicked, it removes all the keys and values saved to localStorage. Now, our little web application is working well.

Conclusion

I'm sure by now you understand what localStorage means and how to utilize it's different methods to store your data. If you don't understand any concept, you can go over the post again. Here are some resources you can checkout out for to know more about localStorage.

My next article would be on how to update and append data to a key in localStorage. Thanks for reading and see you next time😀