@gdjiami/hooks
Version:
react hooks for mygzb.com
80 lines (79 loc) • 3.18 kB
JavaScript
import { __awaiter, __generator, __read, __spread } from "tslib";
import { useState, useCallback, useRef } from 'react';
import useRefProps from './useRefProps';
import useRefState from './useRefState';
import { getUid } from './utils';
function usePromise(action, option) {
var _this = this;
if (option === void 0) { option = { skipOnLoading: true }; }
var actionRef = useRefProps(action);
var optionRef = useRefProps(option);
var currentTaskId = useRef(0);
var _a = __read(useRefState(false), 3), loading = _a[0], setLoading = _a[1], loadingRef = _a[2];
var _b = __read(useState(), 2), value = _b[0], setValue = _b[1];
var _c = __read(useState(), 2), error = _c[0], setError = _c[1];
var caller = useCallback(function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return __awaiter(_this, void 0, void 0, function () {
var taskId, shouldStop, res, err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (loadingRef.current && optionRef.current.skipOnLoading) {
return [2 /*return*/];
}
taskId = getUid();
currentTaskId.current = taskId;
shouldStop = function () { return taskId !== currentTaskId.current; };
_a.label = 1;
case 1:
_a.trys.push([1, 3, 4, 5]);
setLoading(true);
setError(undefined);
return [4 /*yield*/, actionRef.current.apply(actionRef, __spread(args))];
case 2:
res = _a.sent();
if (shouldStop()) {
return [2 /*return*/];
}
setValue(res);
return [2 /*return*/, res];
case 3:
err_1 = _a.sent();
if (shouldStop()) {
return [2 /*return*/];
}
setError(err_1);
throw err_1;
case 4:
if (shouldStop()) {
return [2 /*return*/];
}
setLoading(false);
return [7 /*endfinally*/];
case 5: return [2 /*return*/];
}
});
});
}, []);
var reset = useCallback(function () {
currentTaskId.current = -1;
setLoading(false);
setValue(undefined);
setError(undefined);
}, []);
return {
loading: loading,
error: error,
call: caller,
value: value,
setValue: setValue,
reset: reset,
setError: setError,
setLoading: setLoading,
};
}
export default usePromise;