massive fix
Change-Id: I5972893fc44707bddab7d0014b981ac3097238d6
diff --git a/src/app/hook/useLocalStorage.ts b/src/app/hook/useLocalStorage.ts
index 2b28b01..7628f37 100644
--- a/src/app/hook/useLocalStorage.ts
+++ b/src/app/hook/useLocalStorage.ts
@@ -1,19 +1,51 @@
import { useEffect, useState } from 'react';
-export const useLocalStorage = <T>(key: string): T | null => {
- const [value, setValue] = useState<T | null>(null);
+// export const useLocalStorage = <T>(key: string): T | null => {
+// const [value, setValue] = useState<T | null>(null);
- useEffect(() => {
- if (typeof window !== 'undefined') {
+// useEffect(() => {
+// if (typeof window !== 'undefined') {
+// const item = localStorage.getItem(key);
+// if (item) {
+// try {
+// setValue(JSON.parse(item));
+// console.log(JSON.parse(item));
+// } catch (e) {
+// console.error(`解析 localStorage ${key} 失败`, e);
+// }
+// }
+// }
+// }, [key]);
+
+// return value;
+// };
+
+export const useLocalStorage = <T>(key: string): T | null => {
+ const isClient = typeof window !== 'undefined';
+ const [value, setValue] = useState<T | null>(() => {
+ if (isClient) {
const item = localStorage.getItem(key);
if (item) {
try {
- setValue(JSON.parse(item));
+ return JSON.parse(item);
} catch (e) {
console.error(`解析 localStorage ${key} 失败`, e);
}
}
}
+ return null;
+ });
+
+ useEffect(() => {
+ if (!isClient) return;
+ const item = localStorage.getItem(key);
+ if (item) {
+ try {
+ setValue(JSON.parse(item));
+ } catch (e) {
+ console.error(`解析 localStorage ${key} 失败`, e);
+ }
+ }
}, [key]);
return value;