33 lines
918 B
JavaScript
33 lines
918 B
JavaScript
/* eslint-disable import/prefer-default-export */
|
|
import { useEffect, useState } from 'react';
|
|
import { useStore } from 'stores/hooks';
|
|
import { useDebouncedCallback } from 'use-debounce';
|
|
|
|
const DEBOUNCE_DELAY = 350;
|
|
|
|
export function useValue(valueName) {
|
|
const [localValue, setLocalValue] = useState();
|
|
const { $calculation } = useStore();
|
|
|
|
/** @description subscribe to updates from store */
|
|
useEffect(() => {
|
|
const unsubscribe = $calculation.$values.subscribe(valueName, (value) => setLocalValue(value));
|
|
return unsubscribe;
|
|
});
|
|
|
|
const setStoreValue = useDebouncedCallback(
|
|
(value) => $calculation.$values.setValue(valueName, value),
|
|
DEBOUNCE_DELAY
|
|
);
|
|
|
|
/** @description set local state value to global store */
|
|
useEffect(() => {
|
|
setStoreValue(localValue);
|
|
}, [localValue, setStoreValue]);
|
|
|
|
return {
|
|
value: localValue,
|
|
setValue: (val) => setLocalValue(val),
|
|
};
|
|
}
|