Introduction
window.localStorage
offers a way of persisting data across sessions and is specific to that page that created the entries in the storage.
Examples
localStorage
items are stored as key-value pairs both being valid utf-8
strings(valid JSON
).
1. Store an item
To store an item, we convert the item into a JSON
valid string, then set a key
to uniquely identify this item for retrieval later
const item = { id: 1, name: 'UVSensor' }
// storing the item:
window.localStorage.setItem('sensor', JSON.stringify(item))
From the above snippet, sensor
is the key
, and JSON.stringify(item)
is the value with which the key will be associated with.
2. Retrieve an item
To retrieve an item:
// ...possible portions of code ommitted
const itemJson = window.localStorage.getItem('sensor')
// Parse the item into regular JSON
if(itemJson){
let item = JSON.parse(itemJson)
return item
}
To retrieve an item from `localStorage`, we use the key to which the element was set to.
3. Removing an Item
The syntax for removing an item is as follows:
localStorage.removeItem('sensor')
localStorage
is available off the globalwindow
object, hence callingwindow.localStorage
is unnecessary.
4. Remove all items
The syntax for removing all items is as follows:
window.localStorage.clear(); // removes all the items
For a full article on window.localStorage
check out this article on Web storage API
Things to note
- Never use
localStorage
to store sensitive data - Use a persistent means, a database to store information, if a user clears their browser cache all the information stored shall be lost.