nitro-react/src/hooks/useLocalStorage.ts

45 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';
import { GetLocalStorage, SetLocalStorage } from '../api';
2022-04-20 11:43:44 -04:00
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 = GetLocalStorage<T>(key);
2022-04-20 11:43:44 -04:00
return item ?? initialValue;
2022-04-20 11:43:44 -04:00
}
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') SetLocalStorage(key, valueToStore);
2022-04-20 11:43:44 -04:00
}
catch(error)
{
NitroLogger.error(error);
}
}
return [ storedValue, setValue ];
}
export const useLocalStorage = useLocalStorageState;