Skip to content

Instantly share code, notes, and snippets.

@u007
Created November 22, 2023 06:05
Show Gist options
  • Save u007/23c11dbaa9cc3d7f94986f1c57b825f5 to your computer and use it in GitHub Desktop.
Save u007/23c11dbaa9cc3d7f94986f1c57b825f5 to your computer and use it in GitHub Desktop.
localStorage composable ref
export const useLocal = <T>(field: string, defaultData: T, prefix = 'state.') => {
const value = ref(defaultData)
const name = `${prefix}${field}`
watch(value, (v) => {
// console.log('useLocal updated', name, v)
localStorage.setItem(name, JSON.stringify(v))
}, { deep: true })
if (typeof window === 'undefined') {
return value
}
const localData = localStorage.getItem(name)
if (localData) {
value.value = JSON.parse(localData)
}
return value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment