DEV Community

shubham123
shubham123

Posted on • Updated on

Local Storage

The blog is about how to used local storage?

Initially I don't have any idea about how local storage work? how to use local storage? Then Onkar dada told me to read MDN of local storage.I read it and also watched one video on youtube.

About Local Storage.

Local storage is one of the web storage API in which data is store in the form of key value pairs or we can say it is object of strings.In local storage we can store minimum 10MB data but it is not fixed varying with different different browsers.The key point about local storage is- data is still present in local storage even if user close the window or restart the browser or even shut down the system.Means user can store data in local storage as long as user wants.
With the help of following methods we can perform operations on local storage.

setItem-This is function which take two parameters one is key and another is value.This function will add key value pairs in local storage or update key's value if key already exists.
Ex.localStorage.setItem("name","harry");

getItem-With the help of getItem function we can fetch key's value by passing key to the function.If key is not present in local storage then it will return null.
Ex.localStorage.getItem("name");

removeItem-This function takes parameter as key if key is exists then it will remove key along with value.
Ex.localStorage.removeItem("name");

clear-This function is used to remove all key value pairs from local storage.
Ex.localStorage.clear();


After understanding all above concepts then I started with assignment which was based on local storage.
I used two components.First is about to store the key value pair in localStorage and second is about to access key's value from local storage and import both components in main App component.

In first components I added two inputs and one button.
First input is for key and another is for value and used onChange events on each input.
when user enter key and value then state will get updated.
And onclick of button key value pairs will store in local storage.
display one alert msg here I used toastify which makes alert message attractive and also looks nice.
Image description
In second component I used one input and one button.
Input is for key. Here also used onChange event to update state when use enter key.Onclick of button display one alert msg of key's value if key exist in local storage else show alert of 'Please enter valid key'.

Image description

At the end I used one icon which is for to clear local storage.
onClick of icon display alert msg of 'local storage cleared...'

Image description
Live link

Top comments (0)