refun
Version:
A collection of React Hook-enabled functions that compose harmoniously with each other. Similar to `recompose`, but:
56 lines (48 loc) • 1.84 kB
JavaScript
import { useRef, useEffect } from 'react';
import { EMPTY_OBJECT, NOOP, EMPTY_ARRAY } from 'tsfn';
import { shallowEqualByKeys, unwindGenerator, generatorIdFactory } from './utils';
export var onUpdateAsync = function onUpdateAsync(onUpdateFn, watchKeys) {
return function (props) {
var useEffectFnRef = useRef(NOOP);
var onUnmountRef = useRef(NOOP);
var propsRef = useRef(EMPTY_OBJECT);
var watchValuesRef = useRef(EMPTY_ARRAY);
var isMountedRef = useRef(true);
var createGeneratorRef = useRef(NOOP);
var idsRef = useRef(EMPTY_OBJECT);
if (watchValuesRef.current === EMPTY_ARRAY || !shallowEqualByKeys(propsRef.current, props, watchKeys)) {
watchValuesRef.current = watchKeys.map(function (k) {
return props[k];
});
}
propsRef.current = props;
if (useEffectFnRef.current === NOOP) {
useEffectFnRef.current = function () {
if (createGeneratorRef.current === NOOP) {
createGeneratorRef.current = onUpdateFn(propsRef);
}
if (idsRef.current === EMPTY_OBJECT) {
idsRef.current = generatorIdFactory();
}
var generatorId = idsRef.current.newId();
unwindGenerator(createGeneratorRef.current({
cancelOthers: idsRef.current.switchToGenerator(generatorId),
index: generatorId
}), function () {
return isMountedRef.current && idsRef.current.isGeneratorRunning(generatorId);
});
};
}
useEffect(useEffectFnRef.current, watchValuesRef.current);
if (onUnmountRef.current === NOOP) {
onUnmountRef.current = function () {
return function () {
isMountedRef.current = false;
};
};
}
useEffect(onUnmountRef.current, EMPTY_ARRAY);
return props;
};
};
//# sourceMappingURL=on-update-async.js.map