Storing and retrieving data in Local Storage; JavaScript

Storing and retrieving data in Local Storage; JavaScript

The Web browser offers a way to store a large amount of data in a user's browser without affecting the website's performance. By default, both web storage objects which are local Storage and Session Storage allows us to only store only string key-value pairs.

Local Storage stores data with no expiration date that persists even after the browser window is closed. You have to explicitly remove data either programmatically or by clearing the browser's data. The data is shared among all the sessions of the same origin. Since localStorage persists data with no expiration date, it is useful for storing information such as shopping cart items, user preferences (currency, dark or light color scheme), products bookmarked, or even remembering the user is logged into the website.

The Local Storage methods we are going to use here are:

setItem(key, value) Add a new key-value pair to the storage

getItem(key) Retrieve a value by its key

Now let's see an example.

let userInfo = {name:  'Paul' ,  age: 19 , gender:  'Male',  email: 'paul@random.com'  }

Now to store this particular data in local Storage,

localStorage.setItem("User Info", JSON.stringify(userInfo));

To retrieve the data,

retrieveUserData = localStorage.getItem('userInfo')
console.log(retrieveUserData )

To retrieve the JavaScript object from localStorage, use the getItem() method. You still need to use the JSON.parse() method to parse the JSON string back to an object:

//Retrieve the JSON  string
const getUserData = localStorage.getItem('userInfo')

// Parse the JSON to an object
const parsedData = JSON.parse(getUserData )

console.log(parsedData.name) //Output => Paul

console.log(parsedData .age) //Output => 19

console.log(parsedData.gender) //Output => Male