This commit is contained in:
hailin 2025-03-13 23:58:36 +08:00
parent 7f190d498e
commit f4344e0e67
1 changed files with 56 additions and 20 deletions

View File

@ -1,26 +1,62 @@
"use client"; import { useEffect, useState } from "react";
import { useEffect, useState } from 'react' export const useLocalStorage = <T>(key: string, initialValue: T): [T, (value: T) => void] => {
const [storedValue, setStoredValue] = useState<T>(initialValue);
export const useLocalStorage = <T>(
key: string,
initialValue: T
): [T, (value: T) => void] => {
const [storedValue, setStoredValue] = useState(initialValue)
useEffect(() => { useEffect(() => {
// Retrieve from localStorage if (typeof window !== "undefined") {
const item = window.localStorage.getItem(key) try {
if (item) { const item = window.localStorage.getItem(key);
setStoredValue(JSON.parse(item)) if (item) {
setStoredValue(JSON.parse(item));
}
} catch (error) {
console.error("Error reading localStorage", error);
}
} }
}, [key]) }, [key]);
const setValue = (value: T) => { const setValue = (value: T) => {
// Save state setStoredValue(value);
setStoredValue(value) if (typeof window !== "undefined") {
// Save to localStorage try {
window.localStorage.setItem(key, JSON.stringify(value)) window.localStorage.setItem(key, JSON.stringify(value));
} } catch (error) {
return [storedValue, setValue] console.error("Error writing to localStorage", error);
} }
}
};
return [storedValue, setValue];
};
// "use client";
// import { useEffect, useState } from 'react'
// export const useLocalStorage = <T>(
// key: string,
// initialValue: T
// ): [T, (value: T) => void] => {
// const [storedValue, setStoredValue] = useState(initialValue)
// useEffect(() => {
// // Retrieve from localStorage
// const item = window.localStorage.getItem(key)
// if (item) {
// setStoredValue(JSON.parse(item))
// }
// }, [key])
// const setValue = (value: T) => {
// // Save state
// setStoredValue(value)
// // Save to localStorage
// window.localStorage.setItem(key, JSON.stringify(value))
// }
// return [storedValue, setValue]
// }