blob: 7628f37ebeb892f2650b5846807fc3762daf211d [file] [log] [blame]
LaoeGaocid0773912025-06-09 00:38:40 +08001import { useEffect, useState } from 'react';
2
Seamherbb14ecb2025-06-09 22:37:20 +08003// export const useLocalStorage = <T>(key: string): T | null => {
4// const [value, setValue] = useState<T | null>(null);
LaoeGaocid0773912025-06-09 00:38:40 +08005
Seamherbb14ecb2025-06-09 22:37:20 +08006// useEffect(() => {
7// if (typeof window !== 'undefined') {
8// const item = localStorage.getItem(key);
9// if (item) {
10// try {
11// setValue(JSON.parse(item));
12// console.log(JSON.parse(item));
13// } catch (e) {
14// console.error(`解析 localStorage ${key} 失败`, e);
15// }
16// }
17// }
18// }, [key]);
19
20// return value;
21// };
22
23export const useLocalStorage = <T>(key: string): T | null => {
24 const isClient = typeof window !== 'undefined';
25 const [value, setValue] = useState<T | null>(() => {
26 if (isClient) {
LaoeGaocid0773912025-06-09 00:38:40 +080027 const item = localStorage.getItem(key);
28 if (item) {
29 try {
Seamherbb14ecb2025-06-09 22:37:20 +080030 return JSON.parse(item);
LaoeGaocid0773912025-06-09 00:38:40 +080031 } catch (e) {
32 console.error(`解析 localStorage ${key} 失败`, e);
33 }
34 }
35 }
Seamherbb14ecb2025-06-09 22:37:20 +080036 return null;
37 });
38
39 useEffect(() => {
40 if (!isClient) return;
41 const item = localStorage.getItem(key);
42 if (item) {
43 try {
44 setValue(JSON.parse(item));
45 } catch (e) {
46 console.error(`解析 localStorage ${key} 失败`, e);
47 }
48 }
LaoeGaocid0773912025-06-09 00:38:40 +080049 }, [key]);
50
51 return value;
52};