2019-04-22 18:17:18 -05:00
|
|
|
// 3rd party.
|
|
|
|
import React, {useEffect, useState} from 'react';
|
|
|
|
|
2019-04-24 17:00:50 -05:00
|
|
|
export function usePropertyChange(object, property, defaultValue, reducer) {
|
2019-04-22 18:17:18 -05:00
|
|
|
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);
|
2019-04-22 18:17:18 -05:00
|
|
|
};
|
|
|
|
onValueChanged();
|
|
|
|
object.on(`${property}Changed`, onValueChanged);
|
|
|
|
return () => {
|
|
|
|
object.off(`${property}Changed`, onValueChanged);
|
|
|
|
};
|
|
|
|
}, [object, value]);
|
|
|
|
return value;
|
|
|
|
}
|