2022-04-20 11:43:44 -04:00
|
|
|
import { NitroLogger } from '@nitrots/nitro-renderer';
|
|
|
|
import { Dispatch, SetStateAction, useState } from 'react';
|
2022-08-18 01:31:11 -04:00
|
|
|
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
|
|
|
|
{
|
2022-08-18 01:31:11 -04:00
|
|
|
const item = GetLocalStorage<T>(key);
|
2022-04-20 11:43:44 -04:00
|
|
|
|
2022-08-18 01:31:11 -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
|
|
|
|
2022-08-18 01:31:11 -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;
|