Extract set settings hook
This commit is contained in:
parent
bc1e9abf3e
commit
9bd913e174
1 changed files with 14 additions and 6 deletions
|
@ -1,15 +1,13 @@
|
|||
import { atom, useAtomValue, useSetAtom, WritableAtom } from 'jotai';
|
||||
import { SetAtom } from 'jotai/core/atom';
|
||||
import { selectAtom } from 'jotai/utils';
|
||||
import { useMemo } from 'react';
|
||||
import { Settings } from '../settings';
|
||||
|
||||
export const useSetting = <K extends keyof Settings>(
|
||||
export const useSetSetting = <K extends keyof Settings>(
|
||||
settingsAtom: WritableAtom<Settings, Settings>,
|
||||
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(
|
||||
() =>
|
||||
atom<null, Settings[K]>(null, (get, set, value) => {
|
||||
|
@ -20,7 +18,17 @@ export const useSetting = <K extends keyof Settings>(
|
|||
[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];
|
||||
};
|
||||
|
|
Loading…
Reference in a new issue