Skip to content

Commit e7ac5e3

Browse files
committed
feat: add persistence utilities for recent searches using localStorage
1 parent 1b6745b commit e7ac5e3

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

hooks/useRecentSearches.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,30 @@ export const MAX_SEARCHES = 5;
77

88
type State = { searches: string[]; mounted: boolean };
99

10+
function loadFromStorage(): string[] {
11+
let saved: string[] = [];
12+
try {
13+
const stored = localStorage.getItem(STORAGE_KEY);
14+
if (stored) saved = JSON.parse(stored) as string[];
15+
} catch {
16+
// ignore malformed storage
17+
}
18+
return saved;
19+
}
20+
21+
function writeStorage(searches: string[] | null): void {
22+
try {
23+
if (searches === null) {
24+
localStorage.removeItem(STORAGE_KEY);
25+
return;
26+
}
27+
28+
localStorage.setItem(STORAGE_KEY, JSON.stringify(searches));
29+
} catch {
30+
// ignore storage write failures
31+
}
32+
}
33+
1034
export function useRecentSearches() {
1135
// Always start with [] and mounted:false on both server and client so the
1236
// initial render matches (SSR-safe). A single setState in the mount effect

0 commit comments

Comments
 (0)