Understand the basics of LocalStorage in 5 minute

Understand the basics of LocalStorage in 5 minute

Getting started with Local storage

When building CRUD (CREATE, READ, UPDATE, and DELETE) apps, it is essential that when a user adds an item, that item should still be on the web page even though the user returns days later, refreshes the page or even close the tab. And there is one JavaScript feature that can help us with it. That feature is called localStorage . If you are looking for a way to store data locally without connecting to a server, this article is for you.

What is localStorage ?

localStorage is a type of web storage that allows a user to access a localStorage object and store the data in the browser with no expiration date. This means the data stored in the browser will persist even after the browser window has been closed.

Basically, It is the ability to keep data or information in the browser even though a user reloads the page or closes the entire window.

NOTE: A user cannot access the stored data if they revisit the same site with a different browser or on another device.

💡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 the JSON.stringify() method. We’ll talk more about this later in the article.

💡 It is advised to not store important data of users in localStorage

How to Access the localStorage ?

Here are some steps you need to follow if you want to access the localStorage

Step 1

Open your chrome Dev tools by pressing f12 or ctrl+shift and press i

Step 2

Click on the Application tab and when it opens, you will see Application , Storage and Cache

Step 3

Click on Local Storage under the Storage tab.

Here is a visual representation of the following steps 👇🏽

Step 4

Click on the Local Storage dropdown and further click on the dropdown item. 👇🏽

From the diagram above, you will see that two columns will show after clicking on the dropdown item. Those columns are called, and value pairs and it is where localStorage stores every data you save to it. We are going to look more into it in a minute. But there are two things to note here.

  1. The dropdown item will differ depending on what is on your browser

  2. You can set, and value directly inside the console.

Methods in localStorage

There are five methods in localStorage which are setItem(), getItem(), removeItem() , clear()

1. setItem()

This method is used to store or update data inside the localStorage using key, and value pairs .

The key is what you are going to use when you want to get or remove something, while thevalue is what you are going to get when you get the key item.

It accepts the key as its first argument and then the value as the second argument.

Let’s see an example 👇🏽

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

// console.log(localStorage.name);

// output: lawrence

From the example above, the key is the name while the value is Lawrence.

NOTE: For best practices, it is good to give the key an unique name using namespace or even storing the key inside a variable. The reasons are;

  1. Prevents you from overriding information that is already in the localStorage.

  2. Prevents other websites from overriding your own website storage key.

Let’s see an example 👇🏽

const LOCAL_STORAGE_KEY = 'names.name';

localStorage.setItem(LOCAL_STORAGE_KEY, 'lawrence');

As we talked about earlier in this article, localStorage stores data as a string and the example we just did was a string example. Let’s take another example using objects this time. 👇🏽

const LOCAL_STORAGE_KEY = 'Mytodos.todo';

const todo = {
  id: 1,
  name: 'Play Drums',
  complete: false,
};

localStorage.setItem(LOCAL_STORAGE_KEY, todo);

Let’s see the output in thelocalStorage tab 👇🏽

From the output above, we see that the value is showing object object and it is because we did not convert it to a string first. Let’s convert it to a string and take a look at the output again 👇🏽

const LOCAL_STORAGE_KEY = 'Mytodos.todo';

const todo = {
  id: 1,
  name: 'Play Drums',
  complete: false,
};

localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todo));

Here is the output 👇🏽

2. getItem()

This method is used to retrieve data fromlocalStorage. It accepts a single parameter, which is the key used when saving data.

let’s see how it works using the previous example 👇🏽

const LOCAL_STORAGE_KEY = 'Mytodos.todo';

const todo = {
  id: 1,
  name: 'Play Drums',
  complete: false,
};

const getTodo = localStorage.getItem(LOCAL_STORAGE_KEY);

console.log(getTodo);

//output: {"id":1,"name":"Play Drums","complete":false}

From the example above, we are simply getting the todo that we’ve already stored using setItem() and we are getting the todo using the key.

3. removeItem()

This method is used to remove an item by key from the localStorage. It’s just the opposite of the getItem() . Let’s see how it works still using the previous example 👇🏽

const LOCAL_STORAGE_KEY = 'Mytodos.todo';

const todo = {
  id: 1,
  name: 'Play Drums',
  complete: false,
};

localStorage.removeItem(LOCAL_STORAGE_KEY);

4. clear()

This method is basically used to clear all stored data inlocalStorage.

💡 removeItem() is used to remove only a single data from the localStorage.

5. key()

This method is often used in situations where you need to loop through keys and allows you to pass a number or index to localStorage to retrieve the name of thekey. Let’s see an example 👇🏽

localStorage.setItem('firstname', 'lawrence');
localStorage.setItem('lastname', 'Dev');

console.log(localStorage.key(0));

// output: lawrence

From the example above, we have two stored items which are firstname and lastname. The key() method can be used to get the index of any items stored in thelocalStorage and our case, it is getting the firstname which is lawrence.

💡 The methods you are going to use 99% of the time are the setItem() andgetItem() method.

CONCLUSION

That’s it, gang, I hope you now understand the basics of how the localStorage works. There is also some stuff that I did not cover in this article so don’t just stop learning here. Do more research.

See you next week and have an amazing weekend 😉