refun
Version:
A collection of React Hook-enabled functions that compose harmoniously with each other. Similar to `recompose`, but:
59 lines (46 loc) • 1.87 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.onUpdateAsync = void 0;
var _react = require("react");
var _tsfn = require("tsfn");
var _utils = require("./utils");
const onUpdateAsync = (onUpdateFn, watchKeys) => props => {
const useEffectFnRef = (0, _react.useRef)(_tsfn.NOOP);
const onUnmountRef = (0, _react.useRef)(_tsfn.NOOP);
const propsRef = (0, _react.useRef)(_tsfn.EMPTY_OBJECT);
const watchValuesRef = (0, _react.useRef)(_tsfn.EMPTY_ARRAY);
const isMountedRef = (0, _react.useRef)(true);
const createGeneratorRef = (0, _react.useRef)(_tsfn.NOOP);
const idsRef = (0, _react.useRef)(_tsfn.EMPTY_OBJECT);
if (watchValuesRef.current === _tsfn.EMPTY_ARRAY || !(0, _utils.shallowEqualByKeys)(propsRef.current, props, watchKeys)) {
watchValuesRef.current = watchKeys.map(k => props[k]);
}
propsRef.current = props;
if (useEffectFnRef.current === _tsfn.NOOP) {
useEffectFnRef.current = () => {
if (createGeneratorRef.current === _tsfn.NOOP) {
createGeneratorRef.current = onUpdateFn(propsRef);
}
if (idsRef.current === _tsfn.EMPTY_OBJECT) {
idsRef.current = (0, _utils.generatorIdFactory)();
}
const generatorId = idsRef.current.newId();
(0, _utils.unwindGenerator)(createGeneratorRef.current({
cancelOthers: idsRef.current.switchToGenerator(generatorId),
index: generatorId
}), () => {
return isMountedRef.current && idsRef.current.isGeneratorRunning(generatorId);
});
};
}
(0, _react.useEffect)(useEffectFnRef.current, watchValuesRef.current);
if (onUnmountRef.current === _tsfn.NOOP) {
onUnmountRef.current = () => () => {
isMountedRef.current = false;
};
}
(0, _react.useEffect)(onUnmountRef.current, _tsfn.EMPTY_ARRAY);
return props;
};
exports.onUpdateAsync = onUpdateAsync;