localStorage
can be an incredibly useful tool in creating experiences for applications, extensions, documentation, and a variety of use cases. I’ve personally used it in each! In cases where you’re storing something small for the user that doesn’t need to be kept permanently, localStorage
is our friend. Let’s pair localStorage
with Vue, which I personally find to be a great, and easy-to-read developer experience.
Simplified example
I recently taught a Frontend Masters course where we built an application from start to finish with Nuxt. I was looking for a way that we might be able to break down the way we were building it into smaller sections and check them off as we go, as we had a lot to cover. localStorage
was a gsolition, as everyone was really tracking their own progress personally, and I didn’t necessarily need to store all of that information in something like AWS or Azure.
Here’s the final thing we’re building, which is a simple todo list:
Storing the data
We start by establishing the data we need for all the elements we might want to check, as well as an empty array for anything that will be checked by the user.
export default {
data() {
return {
checked: [],
todos: [
"Set up nuxt.config.js",
"Create Pages",
// ...
]
}
}
}
We’ll also output it to the page in the template tag:
<div id="app">
<fieldset>
<legend>
What we're building
</legend>
<div v-for="todo in todos" :key="todo">
<input
type="checkbox"
name="todo"
:id="todo"
:value="todo"
v-model="checked"
/>
<label :for="todo">{{ todo }}</label>
</div>
</fieldset>
</div>
Mounting and watching
Currently, we’re responding to the changes in the UI, but we’re not yet storing them anywhere. In order to store them, we need to tell localStorage
, “hey, we’re interested in working with you.” Then we also need to hook into Vue’s reactivity to update those changes. Once the component is mounted, we’ll use the mounted
hook to select checked items in the todo list then parse them into JSON so we can store the data in localStorage
:
mounted() {
this.checked = JSON.parse(localStorage.getItem("checked")) || []
}
Now, we’ll watch that checked
property for changes, and if anything adjusts, we’ll update localStorage
as well!
watch: {
checked(newValue, oldValue) {
localStorage.setItem("checked", JSON.stringify(newValue));
}
}
That’s it!
That’s actually all we need for this example. This just shows one small possible use case, but you can imagine how we could use localStorage
for so many performant and personal experiences on the web!
All the checkboxes are tied to the same v-model, so all the boxes check when one is clicked.
I’m not seeing this to be the case- if you check the demo in a debug window: https://cdpn.io/sdras/debug/JjXdNrO then go to Application tab in Chrome DevTools, and then Local Storage, you can see them updating correctly. Let me know if you can reproduce something else, though! Would be interested to see it. Thanks!
Hi, great little tutorial! Just found one small issue: I user initially doesn’t have
checked
in localStorage then on mount he readchecked
asnull
which will be parsed tofalse
causing a bugged behavior where ticking one checkbox checks all the checkboxes. A quick fix would be to fallback to empty array when reading from localStorage.Thanks! updated
For Composition API users there are many options that make it simpler: some work almost as ref() replacements and others already handle syncing data between tabs.
I recently wrote a whole CMS / DB thingo based on LocalStorage and Vue. Sadly it’s not OS yet as the UI kit is currently closed. :(
https://cocktailcms.com/
Love it. Thks! A good start to understand the usage
Before writing to local storage you should probably check if it is possible first, as the quota might be filled or the browser is safari in private browsing mode.
I recently discovered that localStorage isn’t natively present when testing with jest, and it has to be mocked.
https://github.com/d-kochanzhi/LocalStorageAdapter
Nice tutorial. It may be worth mentioning the security concerns of using localStorage as well as consider re-wording the “In cases where you’re storing something small for the user that doesn’t need to be kept permanently, localStorage is our friend.”. localStorage will actually be kept around long after the session has ended unless you manually clear the localStorage. This may give new developers the wrong idea, especially if they start storing JWTs in localStorage — in which case they would want sessionStorage which terminates after the browser tab or window is closed. Otherwise, I really enjoy your writing. Especially your insights with CSS and SVG.