🎨 Improve code readability by reformatting functions and cleaning up whitespace
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* LocalStorage Composable
|
||||
* Type-safe localStorage operations with Vue reactivity
|
||||
*/
|
||||
|
||||
import { ref, watch } from 'vue';
|
||||
|
||||
/**
|
||||
* Use localStorage with reactivity
|
||||
* @param {string} key - Storage key
|
||||
* @param {any} defaultValue - Default value
|
||||
* @returns {Ref} Reactive ref synced with localStorage
|
||||
*/
|
||||
export function useLocalStorage(key, defaultValue) {
|
||||
// Try to load from localStorage
|
||||
const loadValue = () => {
|
||||
try {
|
||||
const item = localStorage.getItem(key);
|
||||
if (item !== null) {
|
||||
return JSON.parse(item);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error loading ${key} from localStorage:`, error);
|
||||
}
|
||||
return defaultValue;
|
||||
};
|
||||
|
||||
const storedValue = ref(loadValue());
|
||||
|
||||
// Watch for changes and save to localStorage
|
||||
watch(
|
||||
storedValue,
|
||||
(newValue) => {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(newValue));
|
||||
} catch (error) {
|
||||
console.error(`Error saving ${key} to localStorage:`, error);
|
||||
}
|
||||
},
|
||||
{ deep: true }
|
||||
);
|
||||
|
||||
return storedValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Manage search history in localStorage
|
||||
* @param {string} key - Storage key
|
||||
* @param {number} maxItems - Maximum number of items to store
|
||||
* @returns {Object} History management functions
|
||||
*/
|
||||
export function useSearchHistory(key = 'searchHistory', maxItems = 5) {
|
||||
const history = useLocalStorage(key, []);
|
||||
|
||||
const addToHistory = (query) => {
|
||||
if (!query || query.trim() === '') return;
|
||||
|
||||
// Remove duplicates and add to front
|
||||
const newHistory = [
|
||||
query,
|
||||
...history.value.filter(item => item !== query)
|
||||
].slice(0, maxItems);
|
||||
|
||||
history.value = newHistory;
|
||||
};
|
||||
|
||||
const removeFromHistory = (query) => {
|
||||
history.value = history.value.filter(item => item !== query);
|
||||
};
|
||||
|
||||
const clearHistory = () => {
|
||||
history.value = [];
|
||||
};
|
||||
|
||||
return {
|
||||
history,
|
||||
addToHistory,
|
||||
removeFromHistory,
|
||||
clearHistory
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user