refactor: replace useLocalStorage with useBrowserStorage

This commit is contained in:
henrygd
2025-09-01 17:28:13 -04:00
parent 3dbcb5d7da
commit d2aed0dc72
4 changed files with 22 additions and 25 deletions

View File

@@ -152,20 +152,20 @@ export function decimalString(num: number, digits = 2) {
return formatter.format(num)
}
/** Get value from local storage */
function getStorageValue(key: string, defaultValue: any) {
const saved = localStorage?.getItem(key)
/** Get value from local or session storage */
function getStorageValue(key: string, defaultValue: any, storageInterface: Storage = localStorage) {
const saved = storageInterface?.getItem(key)
return saved ? JSON.parse(saved) : defaultValue
}
/** Hook to sync value in local storage */
export function useLocalStorage<T>(key: string, defaultValue: T) {
/** Hook to sync value in local or session storage */
export function useBrowserStorage<T>(key: string, defaultValue: T, storageInterface: Storage = localStorage) {
key = `besz-${key}`
const [value, setValue] = useState(() => {
return getStorageValue(key, defaultValue)
return getStorageValue(key, defaultValue, storageInterface)
})
useEffect(() => {
localStorage?.setItem(key, JSON.stringify(value))
storageInterface?.setItem(key, JSON.stringify(value))
}, [key, value])
return [value, setValue]