Learn about using localStorage in Javascript and React

Learn about using localStorage in Javascript and React:

 LocalStorage has four methods.

  1. localStorage.setItem(“data”,data)
  2. localStorage.getItem(“data”)
  3. localStorage.removeItem(“data”)
  4. localStorage.remove()

We will also be using and discussing about JSON.parse() and JSON.stringify() in this post as well.

1. localStorage.setItem(“data”,data)

With setItem() we can set an item to localStorage which will persist even after we reload the page.

Below is an example of it.

A small use case can be when we click on a button, the data can be added to the localStorage.


const click = () =>{
localStorage.setItem('data','data')
}
return(
Click
)

We can set an object,string or even an array to the localStorage.

To know where our localStorage item is located, follow the steps below,

  • Right click and click inspect.
  • Go to application and you will find the items in the website name you are currently in.

2. localStorage.getItem(“data”)

After setting a data we can access the data with localStorage.getItem(“data”)

Here we can get the element as a string with JSON.stringify() or as an object with JSON.parse() from a string.


const data = JSON.stringify(localStorage.getItem('data'))

We can then use this data to map out to the frontend or whatever logic you wish.

3. localStorage.removeItem(“data”)

With localStorage.removeItem(‘data’) we can remove the localStorage item.

Its use case is similar to setItem() as when we want to remove an item, we click a button to do that functionality.


const remove = () =>{
localStorage.removeItem('data')
}
return(
Click
)

4. localStorage.remove()

With this function we can remove all the items in one go.


const removeall = () =>{
localStorage.remove
}
return(
Click
)

And these are some of the methods and usecases on how you can use localStorage in your projects.

As a frontend developer, localStorage is a life saver as you need not know backend and database concepts like node.js and mongodb for using routes like GET,POST in our static app.

from Tumblr https://generouspiratequeen.tumblr.com/post/637023507515047936

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s