Skip to content

Instantly share code, notes, and snippets.

@eru123
Created July 18, 2023 09:51
Show Gist options
  • Save eru123/db2a037eb20ff081d251bbf21232bdcf to your computer and use it in GitHub Desktop.
Save eru123/db2a037eb20ff081d251bbf21232bdcf to your computer and use it in GitHub Desktop.
A Vue 3 composable that can persist state with localStorage
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