Abstract Local Storage in Vue 3

1 month ago
js
// useLocalStorage.js
import { customRef } from 'vue'

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

// 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

Discussions

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