Created
July 18, 2023 09:51
-
-
Save eru123/db2a037eb20ff081d251bbf21232bdcf to your computer and use it in GitHub Desktop.
A Vue 3 composable that can persist state with localStorage
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 { reactive, watch, toRef } from "vue" | |
const state = reactive({}) | |
export const usePersistentData = (key, defaultValue) => { | |
if (state[key]) { | |
const data = toRef(state, key) | |
watch(data, () => { | |
window.localStorage.setItem(key, JSON.stringify(data.value)) | |
}, { deep: true }) | |
return data | |
} else if (window.localStorage.getItem(key)) { | |
state[key] = JSON.parse(window.localStorage.getItem(key)) | |
const data = toRef(state, key) | |
watch(data, () => { | |
window.localStorage.setItem(key, JSON.stringify(data.value)) | |
}, { deep: true }) | |
return data | |
} | |
state[key] = defaultValue | |
window.localStorage.setItem(key, JSON.stringify(defaultValue)) | |
const data = toRef(state, key) | |
watch(data, () => { | |
window.localStorage.setItem(key, JSON.stringify(data.value)) | |
}, { deep: true }) | |
return data | |
} | |
export const deletePersistentData = (key) => { | |
delete state[key] | |
window.localStorage.removeItem(key) | |
} | |
export const clearPersistentData = () => { | |
for (const key in state) { | |
delete state[key] | |
window.localStorage.removeItem(key) | |
} | |
} | |
export default usePersistentData |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment