Store it, locally
I recently learned about a neat little tool called localStorage
, so I figured I would do a little reading on it to gain a clearer understanding, and then try to put that understanding into my own words.
But first, let’s backtrack a bit. So… not in my own words, but according to MDN web docs:
When writing code for the Web, there are a large number of Web APIs available. The Web Storage API provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies.
Brief Overview of Web Storage
There are two different mechanisms for Web Storage — sessionStorage
and localStorage
.
First, let’s take a look at what they both offer:
Storage: ability to set, retrieve, and remove data locally in the browser; data stored is specific to the protocol of the page
Window: an extension of the Window
with the new storage property, and a Window.onstorage
event handler that fires when the storage area changes
StorageEvent: astorage
event fires when the storage area changes (for example, a new item is set to storage).
Strings: only supports key/value strings; other datatypes are automatically converted
Size: most modern browsers allow 2 megabytes of data at minimum
Now, let’s understand the differences:
sessionStorage:
data persists until the browser window is closed
localStorage:
data persists until it is manually cleared, even after browser window is closed + data is shared between all tabs and windows with the same origin
Web Storage Methods
setItem (key, value)
- store the key and value pairgetItem (key)
- retrieve the stored value by the keyremoveItem(key)
- remove the key/value pair by keyclear()
- remove all stored datakey(index)
- retrieve the key on a given positionlength
- returns the number of stored items
Examples
Check if localStorage
is supported in the browser and if anything is currently stored:
Add data tolocalStorage
:
Get data fromlocalStorage
:
Update data inlocalStorage
:
Delete data inlocalStorage
:
Clear all data inlocalStorage
:
Adding JSON objects tolocalStorage
:
Since localStorage
only supportsstrings
, we use JSON.stringify()
to convert our object to a string
However, getting this item again would result in:
"{"toppings":"Pineapple and Ham","scandalous":"very"}"
Get JSON objects fromlocalStorage
:
We use JSON.parse()
to convert the contents back into our datatype.
Use Cases
Web storage is commonly used for saving data such as user preferences, remembering items saved in a shopping cart, and keeping track of that a user is logged in.
Although cookies can be used for similar types of storage, they have significantly lower storage limits, and send data to the server with every HTTP request.
Check out the MDN docs here for further information to help you decide which Web Storage mechanism might be best for your application.