JavaScript Local Storage Explained!

javascript-local-storage-explained!

In the early days of the internet, you needed a server to store data. But nowadays, through LocalStorage, you can store data on browsers and applications without communicating with a back-end server.

In this article, you will learn about the theoretical and practical applications of LocalStorage in JavaScript.

Let’s talk about web storage

Before we hop into the real deal, let’s look at the definition of web storage. Web storage is one of the great features of HTML5 that allows web applications to store data locally within a user’s browser.

The two most common forms of web storage are LocalStorage and Session Storage. The key difference between these two forms of web storage is that data saved in LocalStorage never leaves the browser and remains there until you explicitly remove it. In contrast, data stored in Session Storage is removed once a browser tab/window is closed.

What is Local Storage?

As mentioned earlier, LocalStorage is a form of web storage provided by the browser that allows web applications to store data locally within a user’s browser with no expiration date. Here, stored data will remain available even when you close and re-open a browser tab/window.

Note that the data stored in LocalStorage is only preserved on a user’s browser on the device they used to access a site. Hence, users cannot access the stored data if they revisit the same site later with a different browser or on another device.

LocalStorage Use Cases

The following presents some everyday use cases of LocalStorage.

1. Store Partially Submitted Form Data

If a user fills out a long form online, LocalStorage can be a helpful resource for storing input data. Even if the internet gets disconnected between filling out the form and submitting it, users won’t lose their inputs and can continue from where they left off.

2. Caching

Caching refers to storing data such as login details on a user’s device so that future requests for that data can be served faster. You can use localStorage to cache a website so that users can still access the site even when they are offline.

3. Database for basic applications

As mentioned earlier, data storage was initially only possible by communicating with a database through the backend. But now, with LocalStorage, you can store data without needing a database. Hence LocalStorage can serve as a little database for some basic applications.

How to Access LocalStorage

Accessing LocalStorage is pretty simple and takes only a few steps:

  1. Go to any website or web application and open the browser console by pressing the F12 key.
  2. Next, press the Application tab, and in the menu on the left and you will see LocalStorage under the Storage tab as shown below.

  1. Click on the LocalStorage dropdown and further click on a/the dropdown item.

As can be seen, there are two columns, key, and value. This is where LocalStorage stores every data you save to it.

How to Use Local Storage

You can use following methods to manage data in LocalStorage.

Method Description
setItem() To store data in local storage.
getItem() To get or retrieve the data from local storage
removeItem() To delete data from local storage using a key
key() To retrieve data from local storage at a specified index

setItem( )

This method is used to store data in LocalStorage. It accepts a key as its first argument and then a value as the second argument.

Let’s add an item to localStorage using the following.

localStorage.setItem("name", "Mandy");
// Here, `name` is the key and `Mandy` is the value

As mentioned earlier, LocalStorage stores data as strings, so if you want to save data such as objects and arrays, you need to convert them to strings using JSON.stringify() method.

Let’s see how this works!

//Storing objects in LocalStorage
const user = {
  name: "Mandy",
  age: 23,
};

localStorage.setItem("user-info", JSON.stringify(user));

//Storing arrays/lists in LocalStorage
const names = ["John", "Jake", "Vanessa"];
localStorage.setItem("names", JSON.stringify(names));

getItem()

Use the getItem() method to retrieve data from LocalStorage. This method accepts a single parameter, which is the key used when saving data.

For example, to retrieve data such as the above user object, you will use the following statement:

localStorage.getItem("user-info");

The above code will return a JSON string as shown below:

"{name:"Suzuki", age:"23"}"

You should then convert it to an object using the JSON.parse() method.

JSON.parse(localStorage.getItem('user-info'));

removeItem()

Use the removeItem() method to remove data from LocalStorage. This method accepts a key as a parameter.

For example, you will use the following statement to delete the user object from LocalStorage.

localStorage.removeItem("user-info");

key()

Use key(index) method to retrieve data from LocalStorage, where index represents the nth data you want to retrieve.

localStorage.key(2);

clear()

Use the clear() method to clear out or remove all data from LocalStorage at a particular instance.

localStorage.clear()  

Project

Now that you’ve learnt about the main methods used to manage data in LocalStorage, letโ€™s get our hands dirty by creating a web application where users can:

  • Save data to LocalStorage
  • Retrieve the data
  • Delete the data using a key
  • And also clear out all data from LocalStorage.

Let’s start by creating a new folder and open it in a code editor. Next, create three files, index.html , style.css and main.js.

Letโ€™s Code!

The index.html will contain the HTML markup for the web application. The HTML code comprises a form having various input fields with buttons.



  
     charset="utf-8" />
     name="viewport" content="width=device-width" />
    </span>Local Storage<span class="nt">
     rel="stylesheet" href="style.css" />
  
  
     id="form">
       id="userForm">
        

LocalStorage Application

for="userName">User type="text" id="userName" placeholder="Enter user name" required autofocus /> /> for="age">Age type="number" id="age" placeholder="Enter user age" required /> /> for="key">Key type="text" id="key" placeholder="Enter key" required /> /> type="submit">Save user /> for="key">Enter Key to retrieve user type="text" id="retrieveKey" placeholder="Enter key to access user" required /> /> id="retrieveButton">Retrieve user /> id="userData">
/> for="removeKey">Enter Key to delete user type="text" id="removeKey" placeholder="removeKey" required /> /> id="removeButton">Delete user /> id="clearButton">Delete all users

Here’s the CSS code.

/* base styles  */
html {
  font-size: 67.5%;
}
body {
  font-size: 1.6rem;
  padding: 0;
  margin: 0;
}

/* form   */
#form {
  margin-left: 2rem;
}

Hereโ€™s the main.js file containing all the functions to store, retrieve, and delete data from LocalStorage.

//store user data in the localStorage
function store() {
  var userName = document.getElementById("userName").value;
  var age = document.getElementById("age").value;
  var key = document.getElementById("key").value;

  const user = {
    userName,
    age,
  };

  //convert user object to string and save it
  localStorage.setItem(key, JSON.stringify(user));
}

//retrieve user data from localStorage
function retrieveUserData() {
  let key = document.getElementById("retrieveKey").value;
  console.log("retrive records");
  let userData = localStorage.getItem(key); //searches for the key in localStorage
  let paragraph = document.createElement("p");
  let info = document.createTextNode(userData);
  paragraph.appendChild(info);
  let element = document.getElementById("userData");
  element.appendChild(paragraph);
  retrieveKey.value = "";
}

//delete user data from localStorage
function removeUserData() {
  var removeKey = document.getElementById("removeKey").value;
  localStorage.removeItem(removeKey);
  removeKey.value = "";
}

//delete all user data from localStorage
function deleteAllUserData() {
  localStorage.clear();
}

//ensures the page is fully loaded before functions can be executed.
window.onload = function () {
  document.getElementById("userForm").onsubmit = store;
  document.getElementById("clearButton").onclick = deleteAllUserData;
  document.getElementById("removeButton").onclick = removeUserData;
  document.getElementById("retrieveButton").onclick = retrieveUserData;
};

Results

The following video shows how the application works:

Some Essential Points About LocalStorage

  • Local storage has no data protection and it is therefore not secure to store sensitive data as they can be accessed by anyone.
  • Local storage can only store a maximum of 5MB of data on the browser.

Conclusion

I encourage you to practice and experiment with LocalStorage by using it in your applications. Get used to saving, retrieving, and deleting data from it.

Thanks for reading!

I hope this has been a worthwhile read. Kindly share this article and follow me on Twitter @dboatengx for updates on future posts.

Cheers!

Total
1
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
what-is-a-headless-cms-&-when-should-i-be-using-it?

What is a headless CMS & when should I be using it?

Next Post
introduction-to-ai-&-ml

Introduction to AI & ML

Related Posts