nitro-react/src/hooks/useLocalStorage.ts

44 lines
1.1 KiB
TypeScript
Raw Normal View History

2022-04-20 11:43:44 -04:00
import { NitroLogger } from '@nitrots/nitro-renderer';
import { Dispatch, SetStateAction, useState } from 'react';
const useLocalStorageState = <T>(key: string, initialValue: T): [ T, Dispatch<SetStateAction<T>>] =>
{
2022-07-18 20:48:54 -04:00
const [ storedValue, setStoredValue ] = useState<T>(() =>
2022-04-20 11:43:44 -04:00
{
if(typeof window === 'undefined') return initialValue;
try
{
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
}
catch(error)
{
return initialValue;
}
});
const setValue = (value: T) =>
{
try
{
const valueToStore = value instanceof Function ? value(storedValue) : value;
2022-07-18 20:48:54 -04:00
setStoredValue(valueToStore);
2022-04-20 11:43:44 -04:00
if(typeof window !== 'undefined') window.localStorage.setItem(key, JSON.stringify(valueToStore));
}
catch(error)
{
NitroLogger.error(error);
}
}
return [ storedValue, setValue ];
}
export const useLocalStorage = useLocalStorageState;