64 lines
1.8 KiB
JavaScript
64 lines
1.8 KiB
JavaScript
import { DEFAULT_DEBOUNCE_DELAY } from 'core/constants/debounce';
|
|
import { useEffect, useState } from 'react';
|
|
import { useDebounce } from 'use-debounce/lib';
|
|
import { useStores } from './useStores';
|
|
|
|
export const useStoreValue = ({ computedValue, valueName }) => {
|
|
const { calculationStore } = useStores();
|
|
const [currentValue, setCurrentValue] = useState(undefined);
|
|
const [debouncedValue] = useDebounce(currentValue, DEFAULT_DEBOUNCE_DELAY);
|
|
|
|
const sourceValue = calculationStore.values[valueName];
|
|
|
|
// get value from store
|
|
useEffect(() => {
|
|
if (!computedValue) {
|
|
if (sourceValue !== undefined) {
|
|
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, debouncedValue };
|
|
};
|
|
|
|
export const useTableValue = ({ tableName, rowIndex, propName }) => {
|
|
const { calculationStore } = useStores();
|
|
const [currentValue, setCurrentValue] = useState(undefined);
|
|
const [debouncedValue] = useDebounce(currentValue, DEFAULT_DEBOUNCE_DELAY);
|
|
|
|
const sourceValue =
|
|
calculationStore.tables[tableName].values[rowIndex][propName];
|
|
|
|
// get value from store
|
|
useEffect(() => {
|
|
if (sourceValue !== undefined) {
|
|
setCurrentValue(sourceValue);
|
|
}
|
|
}, [sourceValue]);
|
|
|
|
// set value to store
|
|
useEffect(() => {
|
|
calculationStore.setTableRow(
|
|
{
|
|
tableName,
|
|
rowIndex,
|
|
},
|
|
{ values: { [propName]: debouncedValue } },
|
|
);
|
|
}, [calculationStore, debouncedValue, propName, rowIndex, tableName]);
|
|
|
|
return { value: currentValue, setCurrentValue, debouncedValue };
|
|
};
|