Master the web storage API
Tags: webdev, javascript, tutorial, beginners
Published: 2022-03-13 16:44:36

## What is Web storage?

web storage is a storage location in our browser that can store data locally on our machine.
the web storage api is a small mechanism that the browser uses to securely store key/value pairs.

`Key` : The identifier of a piece of data
`value` : The value corresponding to the defined key

### There are two types of storage in your browser:

**Local Storage:** Maintains storage for a given web page for an unlimited period of time until it is deleted.

**Session Storage:** Maintains storage for given web page until the browser is closed completely.


## Basic Usage

We will use localStorage in our examples. For any key/value pair, the value given must always be a string. Numbers are automatically converted into strings when stored.
Let's say we want to remember the theme one user prefers every time they come back to our web page. We can use localStorage for this:

**Storing Data:**
We use the `.setItem()` method to store a key/value pair. The first parameter of the function is the key, the second is the value we want to assign to it.

```
localStorage.setItem('appTheme', 'dark');
```

**Accessing Data:**

```
console.log(localStorage.getItem('appTheme'));
```

**Accessing the whole Storage object**

```
console.log(localStorage);
```


## Working With Objects

Since we can only store strings inside our browser's storage, we have  to convert any objects we might want to store onto a JSON string:

```
const myData = { name: 'david', job: 'web developer'};
localStorage.setItem('user', JSON.stringify(myData));
```

You can see the changes in your browser's developer tools under the 'application' tab in Chrome or "Storage" tab in Firefox. Notice how the storage in only kept for the web page where we ran our code, the live server localhost:5500.

When you want to read an object that has been stringified, you will need to run `JSON.parse()` like so:
	

```
console.log(JSON.parse(localStorage.getItem('user')));
```


## Deleting Data

Data stored using localStorage will not be deleted until it is deleted manually or the browser's history is erased.
So in order two delete items, we have two methods:

**1. Delete specific items using removeItem()**

```
localStorage.removeItem('appTheme');

```
this allows you to delete an item by specifying the key that belongs to it.

**2. Clear the entire storage for the active web page**

```
localStorage.clear();
```

This method is straight forward and will erase all key/value pairs entirely from the web page's local storage.


## The Storage Event

We can detect storage changes on a web page by using the storage event listener.

Keep in mind that this event will only be triggered when opening two tabs with the same origin, so the same web page. If we make changes to the storage in the first tab, the event will triggered  in the second tab and all other tabs will the same origin. You can use this event like so:

```
window.addEventLister('storage', (e)=>{
console.log(`Storage Event triggered from ${document.title}`)
console.log(e)
});
```

## Other Facts

1. When browsing privately (incognito), localStorage will also be emptied when you close the browser, in the same way as `sessionStorage` is deleted.

2. With little setup, localStorage can be succesfully used as a small database for basic practice projects and you can implement a full CRUD functionality using it.

3. The browser's web page storage is actually an object, so you can treat it like one and perform actions such as:

```
localStorage.appTheme = 'dark':
localStorage['userName'] = 'david';
		
//using object methods
console.log(Object.values(localStorage))
```

However, it is best to use the setItem and getItem methods to avoid possible problems.

##Wrapping Up
I hope you enjoyed the article, if yes then don't forget to press ❤️ and Subscribe. You can also bookmark it for later use. It was fun to create this article and If you have any queries or suggestions don't hesitate to drop them. See you.
You can extend your support by giving me stars on GitHub Profile.😊👇
[G i t h u b](https://github.com/Mohammad-Asif-Web)
[P o r t f o l i o](https://muhammadasif10.blogspot.com/)
[L i n k e d i n](https://www.linkedin.com/in/mohammadasif10/)

##Support

[Buy me a Coffee](https://www.buymeacoffee.com/muhammadasif10)