Using LocalStorage to store data

Using LocalStorage to store data

Introduction

Local storage is a web storage API for storing data locally on the user's computer. Local storage can only store string data and the data is only accessible to JavaScript within that domain that is each website has personal local storage.

Storing Data in LocalStorage

The Syntax used for storing data in the domain local storage is setItem() and it takes a value and a key.

Key is the name of the value you want to store and value is the name of the value.

localStorage.setItem("key", "value")

Retrieve the data stored in LocalStorage

To retrieve the data stored in the local storage, we need the key we used in storing the data. The Syntax used in retrieving the data is getItem().

localStorage.getItem("key")

Deleting the data stored in the LocalStorage

The Syntax used for deleting data in the local storage is removeItem() and it also requires the key we use for storing the data.

localStorage.removeItem("key")

Clearing all the data stored in the LocalStorage

They might be a scenario where you will need to clear all the data stored in the local storage. The Syntax used is clear(). It doesn't need any key since we are clearing everything in the local storage

localStorage.clear()

Note: You can only store data in localStorage in string format. so if you want to store anything other than a string, you will have to convert them into a string first and then convert the data back to its original state when you retrieve it.

const value={id:1,name:colTheDeveloper}

//storing a data that is not a string
localStorage.setItem("key",JSON.stringify(value))

//Retrieving the data 
JSON.parse(localStorage.getItem("key"))

Conclusion

In this article, we learn how to store, retrieve, delete and clear data in a localStorage. The data stored in local storage is vulnerable to cross-site scripting (XSS) attacks, and being cleared by the user or the browser, which can cause data loss or inconsistency.

I hope you find this article helpful and if there is a problem whatsoever with the article, let me know in the comments. Thanks