JAVASCRIPT
Create a Reusable Vue 3 useLocalStorage Composable
Develop a custom Vue 3 composable `useLocalStorage` to easily persist and retrieve reactive state in the browser's local storage, enhancing data persistence across page reloads.
// src/composables/useLocalStorage.js
import { ref, watch, onMounted, onUnmounted } from 'vue';
export function useLocalStorage(key, defaultValue) {
const storedValue = ref(defaultValue);
// Function to read from localStorage
const read = () => {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : defaultValue;
} catch (error) {
console.error(`Error reading localStorage key “${key}”:`, error);
return defaultValue;
}
};
// Set initial value on mount
onMounted(() => {
storedValue.value = read();
// Listen for changes from other tabs/windows
window.addEventListener('storage', handleStorageChange);
});
onUnmounted(() => {
window.removeEventListener('storage', handleStorageChange);
});
// Watch for changes to the ref and update localStorage
watch(storedValue, (newValue) => {
try {
localStorage.setItem(key, JSON.stringify(newValue));
} catch (error) {
console.error(`Error writing to localStorage key “${key}”:`, error);
}
}, { deep: true }); // Use deep: true for objects/arrays
// Handle changes from other tabs/windows
const handleStorageChange = (event) => {
if (event.key === key) {
storedValue.value = event.newValue ? JSON.parse(event.newValue) : defaultValue;
}
};
return storedValue;
}
// Example usage in a component:
/*
// src/components/SettingsComponent.vue
<template>
<div>
<label>
<input type="checkbox" v-model="darkMode" /> Dark Mode
</label>
<p>Your name: <input type="text" v-model="userName" /></p>
<p>Settings saved to local storage automatically!</p>
</div>
</template>
<script setup>
import { useLocalStorage } from '../composables/useLocalStorage';
const darkMode = useLocalStorage('app-dark-mode', false);
const userName = useLocalStorage('user-name', 'Guest');
</script>
*/
How it works: This snippet provides a reusable Vue 3 composable, `useLocalStorage`, designed to make interacting with the browser's local storage reactive and effortless. It automatically synchronizes a reactive `ref` with a local storage key, reading on mount and writing on change. The composable also includes error handling for parsing and stringifying, and listens for 'storage' events to keep state synchronized across different tabs or windows, making it robust for user preferences or session data.