This repository has been archived on 2025-05-09. You can view files and clone it, but cannot push or open issues or pull requests.
EvoCalculator/src/client/hooks/useStoreValue.js
2020-09-02 17:36:13 +03:00

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 };
};