grungnet/src/hooks/useSetting.ts

25 lines
694 B
TypeScript
Raw Normal View History

import get from "lodash.get";
import set from "lodash.set";
import { useSettings } from "../contexts/SettingsContext";
/**
* Helper to get and set nested settings that are saved in local storage
2021-07-12 22:59:28 +00:00
* @param {string} path The path to the setting within the Settings object provided by the SettingsContext
*/
2021-07-12 22:59:28 +00:00
function useSetting<Type>(path: string): [Type, (value: Type) => void] {
const { settings, setSettings } = useSettings();
2021-07-12 22:59:28 +00:00
const setting = get(settings, path) as Type;
2021-07-12 22:59:28 +00:00
const setSetting = (value: Type) =>
setSettings((prev) => {
const updated = set({ ...prev }, path, value);
return updated;
});
return [setting, setSetting];
}
export default useSetting;