humus-old/client/ui/hooks/use-property-change.js

22 lines
590 B
JavaScript
Raw Normal View History

// 3rd party.
import React, {useEffect, useState} from 'react';
2019-04-24 17:00:50 -05:00
export function usePropertyChange(object, property, defaultValue, reducer) {
const [value, setValue] = useState(defaultValue);
useEffect(() => {
if (!object) {
return;
}
const onValueChanged = () => {
2019-04-24 17:00:50 -05:00
const newValue = object[property];
setValue(reducer ? reducer(newValue) : newValue);
};
onValueChanged();
object.on(`${property}Changed`, onValueChanged);
return () => {
object.off(`${property}Changed`, onValueChanged);
};
}, [object, value]);
return value;
}