2022-05-17 18:30:47 +03:00

63 lines
1.5 KiB
JavaScript

import { computed } from 'mobx';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useStore } from 'stores/hooks';
import { useDebouncedCallback } from 'use-debounce';
const WAIT = 350;
const MAX_WAIT = 1500;
export function useValue(valueName) {
const [value, setValue] = useState();
const { $calculation } = useStore();
const setStoreValue = useCallback(
(val) => $calculation.$values.setValue(valueName, val),
[$calculation.$values, valueName]
);
const debouncedSetStoreValue = useDebouncedCallback(setStoreValue, WAIT, {
maxWait: MAX_WAIT,
});
/** Set local value to global store */
useEffect(() => {
debouncedSetStoreValue(value);
}, [debouncedSetStoreValue, value]);
const storeValue = useMemo(
() => computed(() => $calculation.$values.getValue(valueName)),
[$calculation.$values, valueName]
).get();
/** Set initial value from global store to local state (only once) */
useEffect(
() => {
setValue(storeValue);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);
/** Get global store value and set it to local state */
useEffect(() => {
if (!debouncedSetStoreValue.isPending()) {
setValue(storeValue);
}
}, [debouncedSetStoreValue, storeValue]);
return {
value,
setValue,
};
}
export function useComputedValue(valueName) {
const { $calculation } = useStore();
const computedValue = $calculation.$values.$computed[valueName];
return {
computedValue,
};
}