@gdjiami/hooks
Version:
react hooks for mygzb.com
129 lines (105 loc) • 3.13 kB
JavaScript
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { useState, useCallback, useRef } from 'react';
import useRefProps from './useRefProps';
import useRefState from './useRefState';
import { getUid } from './utils';
function usePromise(action, option) {
if (option === void 0) {
option = {
skipOnLoading: true
};
}
var actionRef = useRefProps(action);
var optionRef = useRefProps(option);
var currentTaskId = useRef(0);
var _useRefState = useRefState(false),
loading = _useRefState[0],
setLoading = _useRefState[1],
loadingRef = _useRefState[2];
var _useState = useState(),
value = _useState[0],
setValue = _useState[1];
var _useState2 = useState(),
error = _useState2[0],
setError = _useState2[1];
var caller = useCallback(function _callee() {
var taskId,
shouldStop,
res,
_args = arguments;
return _regeneratorRuntime.async(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!(loadingRef.current && optionRef.current.skipOnLoading)) {
_context.next = 2;
break;
}
return _context.abrupt("return");
case 2:
taskId = getUid();
currentTaskId.current = taskId;
shouldStop = function shouldStop() {
return taskId !== currentTaskId.current;
};
_context.prev = 5;
setLoading(true);
setError(undefined);
_context.next = 10;
return _regeneratorRuntime.awrap(actionRef.current.apply(actionRef, _args));
case 10:
res = _context.sent;
if (!shouldStop()) {
_context.next = 13;
break;
}
return _context.abrupt("return");
case 13:
setValue(res);
return _context.abrupt("return", res);
case 17:
_context.prev = 17;
_context.t0 = _context["catch"](5);
if (!shouldStop()) {
_context.next = 21;
break;
}
return _context.abrupt("return");
case 21:
setError(_context.t0);
throw _context.t0;
case 23:
_context.prev = 23;
if (!shouldStop()) {
_context.next = 26;
break;
}
return _context.abrupt("return");
case 26:
setLoading(false);
return _context.finish(23);
case 28:
case "end":
return _context.stop();
}
}
}, null, null, [[5, 17, 23, 28]]);
}, []);
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;