-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseLastViewedHanzi.ts
43 lines (37 loc) · 1.23 KB
/
useLastViewedHanzi.ts
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
import { create } from "zustand";
interface LastViewedHanziState {
lastViewedHanzi: {
character: string;
pathname: string;
} | null;
actions: {
handleValueMismatch: () => void;
hydrateLastViewedHanzi: () => void;
};
}
export const LAST_VIEWED_HANZI_KEY = "last-viewed-hanzi";
const useLastViewedHanziStore = create<LastViewedHanziState>()((set) => ({
lastViewedHanzi: null,
actions: {
handleValueMismatch: () => {
try {
const lastViewedHanzi = localStorage.getItem(LAST_VIEWED_HANZI_KEY);
if (lastViewedHanzi) {
!JSON.parse(lastViewedHanzi).pathname && localStorage.removeItem(LAST_VIEWED_HANZI_KEY);
}
} catch {
localStorage.removeItem(LAST_VIEWED_HANZI_KEY);
}
},
hydrateLastViewedHanzi: () =>
set((_) => {
const lastViewedHanzi = localStorage.getItem(LAST_VIEWED_HANZI_KEY);
if (!lastViewedHanzi) return { lastViewedHanzi: null };
return {
lastViewedHanzi: JSON.parse(lastViewedHanzi),
};
}),
},
}));
export const useLastViewedHanzi = () => useLastViewedHanziStore((state) => state.lastViewedHanzi);
export const useLastViewedHanziActions = () => useLastViewedHanziStore((state) => state.actions);