Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Abstraction of the local storage using Vue3's composition API
<script setup>
import useLocalStorage from './useLocalStorage'
const publicKey = useLocalStorage('solana-wallet-public-key')
</script>
<template>
<div>
<input type="text" v-model="publicKey">
<div v-text="publicKey"></div>
</div>
</template>
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()
},
}))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment