Local Storage:
Local Storage is an API provided by browsers that allows you to create, read, update and delete records in the browser. These records are limited to the browser only, meaning data stored in chrome is not available on firefox and vice versa
Before We start
The local storage data is in JSON format, which means when storing the data, we need to convert the JavaScript Object to a JSON format and vice versa.
const person={
name: "Jack Pritom Soren"
}
const personToJson = JSON.stringify(person)
Visual View
Open Developer tools
Go to Application tab
Select Local Storage
Create New Record:
const person={
name: "Jack Pritom Soren"
}
const personToJson = JSON.stringify(person)
localStorage.setItem("person",personToJson)
Read a Record:
const personToJson = localStorage.getItem("person")
const JsonToPerson = JSON.parse(personToJson)
console.log(JsonToPerson)
Update a Record:
const person={
name: "Jack Pritom Soren",
country: "Bangladesh"
}
const personToJson = JSON.stringify(person)
localStorage.setItem("person",personToJson)
Delete a Record:
localStorage.removeItem("person")
Top comments (2)
I would recommend caution with using LocalStorage, while yes - you can absolutely do everything you've described, it's a volatile storage space and there are known instances where an Operating System or Browser ran out of memory and recycled space used by LocalStorage, corrupting the data that was previously set.
I encountered this with a PWA a few years ago, Android would recycle the space where I had a token stored and then calls to the server wouldn't work.
Bugs aside though - sharing this knowledge is still beneficial and I hope you continue to do so 😎
Localstorage is ok to use for key-value data. But as soon as you store more complex documents, you should switch to an async storage like IndexedDB or RxDB