Last active
September 28, 2025 23:53
-
-
Save grocco/5ba49ffff0db22ac7961b3295969e793 to your computer and use it in GitHub Desktop.
Vue@3 useLocalStorage composable
This file contains hidden or 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 { onMounted, onUnmounted, ref, watch } from 'vue'; | |
| export function useLocalStorage(key: string, defaultValue: any = null, deep = false) { | |
| let initialValue; | |
| try { | |
| initialValue = JSON.parse(localStorage.getItem(key) || "null") || defaultValue | |
| } catch (e) { | |
| initialValue = defaultValue | |
| } | |
| const item = ref(initialValue); | |
| watch(item, (value) => { | |
| if (!value) localStorage.removeItem(key); | |
| else localStorage.setItem(key, JSON.stringify(value)) | |
| }, { deep }) | |
| const handleStorageChange = (event: StorageEvent) => { | |
| if (event.key === key) { | |
| try { | |
| item.value = JSON.parse(event.newValue || "null") | |
| } catch (e) { | |
| console.log("ERROR parsing local storage value") | |
| item.value = defaultValue | |
| } | |
| } | |
| }; | |
| onMounted(() => { | |
| window.addEventListener('storage', handleStorageChange); | |
| }); | |
| onUnmounted(() => { | |
| window.removeEventListener('storage', handleStorageChange); | |
| }); | |
| return item; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment