Extract set settings hook

This commit is contained in:
Ajay Bura 2022-12-31 19:10:00 +05:30
parent bc1e9abf3e
commit 9bd913e174

View file

@ -1,15 +1,13 @@
import { atom, useAtomValue, useSetAtom, WritableAtom } from 'jotai'; import { atom, useAtomValue, useSetAtom, WritableAtom } from 'jotai';
import { SetAtom } from 'jotai/core/atom';
import { selectAtom } from 'jotai/utils'; import { selectAtom } from 'jotai/utils';
import { useMemo } from 'react'; import { useMemo } from 'react';
import { Settings } from '../settings'; import { Settings } from '../settings';
export const useSetting = <K extends keyof Settings>( export const useSetSetting = <K extends keyof Settings>(
settingsAtom: WritableAtom<Settings, Settings>, settingsAtom: WritableAtom<Settings, Settings>,
key: K key: K
): [Settings[K], (value: Settings[K]) => void] => { ) => {
const selector = useMemo(() => (s: Settings) => s[key], [key]);
const setting = useAtomValue(selectAtom(settingsAtom, selector));
const setterAtom = useMemo( const setterAtom = useMemo(
() => () =>
atom<null, Settings[K]>(null, (get, set, value) => { atom<null, Settings[K]>(null, (get, set, value) => {
@ -20,7 +18,17 @@ export const useSetting = <K extends keyof Settings>(
[settingsAtom, key] [settingsAtom, key]
); );
const setter = useSetAtom(setterAtom); return useSetAtom(setterAtom);
};
export const useSetting = <K extends keyof Settings>(
settingsAtom: WritableAtom<Settings, Settings>,
key: K
): [Settings[K], SetAtom<Settings[K], void>] => {
const selector = useMemo(() => (s: Settings) => s[key], [key]);
const setting = useAtomValue(selectAtom(settingsAtom, selector));
const setter = useSetSetting(settingsAtom, key);
return [setting, setter]; return [setting, setter];
}; };