Spaces:
Running
Running
File size: 1,531 Bytes
0dd2082 4dae2f7 0dd2082 4dae2f7 0dd2082 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | import { useState, useEffect } from 'react';
const STORAGE_KEY = 'redthread_history';
const MAX_ENTRIES = 50;
export default function useSearchHistory() {
const [history, setHistory] = useState([]);
const [mounted, setMounted] = useState(false);
// Load initial history on mount
useEffect(() => {
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
setHistory(JSON.parse(stored));
}
} catch (err) {
console.warn('Could not load history from localStorage', err);
}
setMounted(true);
}, []);
// Save history when it changes (but only after initial mount)
useEffect(() => {
if (!mounted) return;
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(history));
} catch (err) {
/* quota exceeded — silently fail */
}
}, [history, mounted]);
function addEntry(query, intent, resultCount) {
setHistory(prev => {
const entry = {
id: Date.now(),
query,
intent,
resultCount,
timestamp: new Date().toISOString(),
};
return [entry, ...prev].slice(0, MAX_ENTRIES);
});
}
function clearHistory() {
setHistory([]);
}
function removeEntry(id) {
setHistory(prev => prev.filter(e => e.id !== id));
}
return { history, addEntry, clearHistory, removeEntry };
}
|