33 lines
977 B
JavaScript
33 lines
977 B
JavaScript
import { useStores } from './useStores';
|
|
import { useState, useEffect } from 'react';
|
|
import { useDebounce } from 'use-debounce/lib';
|
|
import { DEBOUNCE_DELAY } from 'constants/debounce';
|
|
|
|
export const useStoreValue = ({ computedValue, valueName }) => {
|
|
const { calculationStore } = useStores();
|
|
const [currentValue, setCurrentValue] = useState(undefined);
|
|
const [debouncedValue] = useDebounce(currentValue, DEBOUNCE_DELAY);
|
|
|
|
const sourceValue = calculationStore.values[valueName];
|
|
|
|
// get value from store
|
|
useEffect(() => {
|
|
if (!computedValue) {
|
|
setCurrentValue(sourceValue);
|
|
}
|
|
}, [computedValue, sourceValue]);
|
|
|
|
// set value to store
|
|
useEffect(() => {
|
|
if (!computedValue) {
|
|
calculationStore.setValue(valueName, debouncedValue);
|
|
}
|
|
}, [calculationStore, computedValue, debouncedValue, valueName]);
|
|
|
|
const value = computedValue
|
|
? calculationStore[computedValue]()
|
|
: currentValue;
|
|
|
|
return { value, setCurrentValue };
|
|
};
|