2019-08-09 10:17:04 +00:00
|
|
|
import { useState } from "react";
|
|
|
|
|
|
|
|
export type SetLocalStorageValue<T> = T | ((prevValue: T) => T);
|
|
|
|
export type SetLocalStorage<T> = (value: SetLocalStorageValue<T>) => void;
|
|
|
|
export default function useLocalStorage<T>(
|
|
|
|
key: string,
|
|
|
|
initialValue: T
|
|
|
|
): [T, SetLocalStorage<T>] {
|
|
|
|
const [storedValue, setStoredValue] = useState<T>(() => {
|
2020-11-23 09:39:24 +00:00
|
|
|
let result: T;
|
|
|
|
try {
|
|
|
|
const item = window.localStorage.getItem(key);
|
|
|
|
result = item ? JSON.parse(item) : initialValue;
|
|
|
|
} catch {
|
|
|
|
result = initialValue;
|
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
2019-08-09 10:17:04 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
const setValue = (value: SetLocalStorageValue<T>) => {
|
|
|
|
const valueToStore = value instanceof Function ? value(storedValue) : value;
|
|
|
|
setStoredValue(valueToStore);
|
2020-11-23 09:39:24 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
window.localStorage.setItem(key, JSON.stringify(valueToStore));
|
|
|
|
} catch {
|
|
|
|
console.warn(`Could not save ${key} to localStorage`);
|
|
|
|
}
|
2019-08-09 10:17:04 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
return [storedValue, setValue];
|
|
|
|
}
|