Abstract Local Storage in Vue 3

3 months ago
// useLocalStorage.js
import { customRef } from 'vue'

export default function (key, defaultValue) {
    return customRef((track, trigger) => ({
        get: () => {
            const value = localStorage.getItem(key)
            return value ? JSON.parse(value) : defaultValue
        set: value => {
            if (value === null) {
            } else {
                localStorage.setItem(key, JSON.stringify(value))

// YourComponent.vue
import useLocalStorage from './useLocalStorage'
const publicKey = useLocalStorage('app-public-key', 'default value')

Provide a unique key and a default value to this function and it'll return a special reference that updates the local storage as you update it.

See code as a Gist


Would you like to chime in?

You must be a member to start a new discussion.

Fortunately, it only takes two click to become one. See you on the other side! 🌸

Become a Member