Last active
May 24, 2024 21:25
-
-
Save lorisleiva/ac21f8492f9e74ddb8a565e054188d1c to your computer and use it in GitHub Desktop.
Abstraction of the local storage using Vue3's composition API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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