Skip to content

Instantly share code, notes, and snippets.

@lorisleiva
Last active May 24, 2024 21:25
Show Gist options
  • Save lorisleiva/ac21f8492f9e74ddb8a565e054188d1c to your computer and use it in GitHub Desktop.
Save lorisleiva/ac21f8492f9e74ddb8a565e054188d1c to your computer and use it in GitHub Desktop.
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