mirror of
https://github.com/cpvalente/ontime.git
synced 2026-08-03 06:28:01 +00:00
9b5d536378
* refactor: cleanup project entry point * refactor: remove unused * refactor: folder restructure
38 lines
981 B
JavaScript
38 lines
981 B
JavaScript
import { useState } from 'react';
|
|
|
|
// Roughly from useHooks - useLocalStorage
|
|
|
|
/**
|
|
* @description utility hook to handle state in local storage
|
|
* @param key
|
|
* @param initialValue
|
|
*/
|
|
export const useLocalStorage = (key, initialValue) => {
|
|
const [storedValue, setStoredValue] = useState(() => {
|
|
try {
|
|
const item = window.localStorage.getItem(`ontime-${key}`);
|
|
return item ? JSON.parse(item) : initialValue;
|
|
} catch (error) {
|
|
return initialValue;
|
|
}
|
|
});
|
|
|
|
/**
|
|
* @description Set value to local storage
|
|
* @param value
|
|
*/
|
|
const setValue = (value) => {
|
|
try {
|
|
// Allow value to be a function so we have same API as useState
|
|
const valueToStore =
|
|
value instanceof Function ? value(storedValue) : value;
|
|
|
|
setStoredValue(valueToStore);
|
|
window.localStorage.setItem(`ontime-${key}`, JSON.stringify(valueToStore));
|
|
} catch (error) {
|
|
console.log(error);
|
|
}
|
|
};
|
|
return [storedValue, setValue];
|
|
}
|