Loading

How to use Local Storage

How to use Local Storage

Local Storage is used to store the data locally in the client's browser. Local Storage data not removed even page refresh or browser close. So you don't need to store temporary data in cookie any more you can use local storage. It stores data in key-value pair and it only stores string value so if you want to store array or object you first need to convert it as a string using JSON.stringify () method & use JSON.parse() to retrieve your actual data.

There are four methods that are available for local storage

setItem(): Save key & value to local storage
getItem(): Get the local storage data value by key
removeItem(): Delete local storage data by key
clear(): Remove all local storage data assign to that URL

You may like: Introduction to Angular's Directive

Example Setting data to local storage

localStorage.setItem('id','1');

To view the local storage data open the browser and go to application tab you will see the local storage id

To fetch the local storage data to your application

let id = localStorage.getItem('id');
console.log(id);
//output 1

To remove the local storage

localStorage.removeItem('id');

If you want to remove the all local storage data when user logout form application

localStorage.clear();

That's it.

Now I am going to show you how to store an object in local storage & retrieve the object in the application.

let users = {
    'name'     : 'Abhay Singh',
    'city'     : 'Kolkata',
    'coountry' : 'India'
}

localStorage.setItem('users',JSON.stringify(users));

To retrieve the objects from the application

if(localStorage.getItem('users') !== null){
    this.usersArray = JSON.parse(localStorage.getItem('users'))
}

I hope this will help you!

You may like: 10 most useful JavaScript array methods

Related Articles