@td-design/rn-hooks
Version:
从ahooks里面抽取的一些在rn项目里可以使用的hooks。提高开发效率
60 lines (57 loc) • 2.37 kB
JavaScript
import { __spreadArray, __read } from '../../_virtual/_tslib.js';
import { useRef, useMemo, useEffect } from 'react';
import { debounce } from 'lodash-es';
var useDebouncePlugin = function (fetchInstance, _a) {
var debounceWait = _a.debounceWait, debounceLeading = _a.debounceLeading, debounceTrailing = _a.debounceTrailing, debounceMaxWait = _a.debounceMaxWait;
var debounceRef = useRef();
var options = useMemo(function () {
var settings = {};
if (debounceLeading !== undefined) {
settings.leading = debounceLeading;
}
if (debounceTrailing !== undefined) {
settings.trailing = debounceTrailing;
}
if (debounceMaxWait !== undefined) {
settings.maxWait = debounceMaxWait;
}
return settings;
}, [debounceLeading, debounceTrailing, debounceMaxWait]);
useEffect(function () {
if (debounceWait) {
var originRunAsync_1 = fetchInstance.runAsync.bind(fetchInstance);
debounceRef.current = debounce(function (cb) {
cb();
}, debounceWait, options);
fetchInstance.runAsync = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new Promise(function (resolve, reject) {
var _a;
(_a = debounceRef.current) === null || _a === void 0 ? void 0 : _a.call(debounceRef, function () {
originRunAsync_1.apply(void 0, __spreadArray([], __read(args), false)).then(resolve)
.catch(reject);
});
});
};
return function () {
var _a;
(_a = debounceRef.current) === null || _a === void 0 ? void 0 : _a.cancel();
fetchInstance.runAsync = originRunAsync_1;
};
}
return function () { };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [debounceWait, options]);
if (!debounceWait)
return {};
return {
onCancel: function () {
var _a;
(_a = debounceRef.current) === null || _a === void 0 ? void 0 : _a.cancel();
},
};
};
export { useDebouncePlugin };