51 lines
1.4 KiB
TypeScript
51 lines
1.4 KiB
TypeScript
'use client'
|
|
|
|
import { useState, useEffect } from 'react'
|
|
|
|
export function useLocalStorage<T>(key: string, initialValue: T) {
|
|
// 获取初始值
|
|
const [storedValue, setStoredValue] = useState<T>(() => {
|
|
if (typeof window === 'undefined') {
|
|
return initialValue
|
|
}
|
|
try {
|
|
const item = window.localStorage.getItem(key)
|
|
return item ? JSON.parse(item) : initialValue
|
|
} catch (error) {
|
|
console.log(error)
|
|
return initialValue
|
|
}
|
|
})
|
|
|
|
// 监听其他标签页的更改
|
|
useEffect(() => {
|
|
function handleStorageChange(e: StorageEvent) {
|
|
if (e.key === key) {
|
|
try {
|
|
const item = e.newValue
|
|
setStoredValue(item ? JSON.parse(item) : initialValue)
|
|
} catch (error) {
|
|
console.log(error)
|
|
}
|
|
}
|
|
}
|
|
|
|
window.addEventListener('storage', handleStorageChange)
|
|
return () => window.removeEventListener('storage', handleStorageChange)
|
|
}, [key, initialValue])
|
|
|
|
// 更新存储的值
|
|
const setValue = (value: T | ((val: T) => T)) => {
|
|
try {
|
|
const valueToStore = value instanceof Function ? value(storedValue) : value
|
|
setStoredValue(valueToStore)
|
|
if (typeof window !== 'undefined') {
|
|
window.localStorage.setItem(key, JSON.stringify(valueToStore))
|
|
}
|
|
} catch (error) {
|
|
console.log(error)
|
|
}
|
|
}
|
|
|
|
return [storedValue, setValue] as const
|
|
}
|