1 | "use strict";
|
---|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
---|
3 | var tslib_1 = require("tslib");
|
---|
4 | var react_1 = require("react");
|
---|
5 | var useMountedState_1 = tslib_1.__importDefault(require("./useMountedState"));
|
---|
6 | function useAsyncFn(fn, deps, initialState) {
|
---|
7 | if (deps === void 0) { deps = []; }
|
---|
8 | if (initialState === void 0) { initialState = { loading: false }; }
|
---|
9 | var lastCallId = react_1.useRef(0);
|
---|
10 | var isMounted = useMountedState_1.default();
|
---|
11 | var _a = react_1.useState(initialState), state = _a[0], set = _a[1];
|
---|
12 | var callback = react_1.useCallback(function () {
|
---|
13 | var args = [];
|
---|
14 | for (var _i = 0; _i < arguments.length; _i++) {
|
---|
15 | args[_i] = arguments[_i];
|
---|
16 | }
|
---|
17 | var callId = ++lastCallId.current;
|
---|
18 | if (!state.loading) {
|
---|
19 | set(function (prevState) { return (tslib_1.__assign(tslib_1.__assign({}, prevState), { loading: true })); });
|
---|
20 | }
|
---|
21 | return fn.apply(void 0, args).then(function (value) {
|
---|
22 | isMounted() && callId === lastCallId.current && set({ value: value, loading: false });
|
---|
23 | return value;
|
---|
24 | }, function (error) {
|
---|
25 | isMounted() && callId === lastCallId.current && set({ error: error, loading: false });
|
---|
26 | return error;
|
---|
27 | });
|
---|
28 | }, deps);
|
---|
29 | return [state, callback];
|
---|
30 | }
|
---|
31 | exports.default = useAsyncFn;
|
---|