@anb98/react-hooks
Version:
Custom hooks for react
67 lines • 3.14 kB
JavaScript
;
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = require("react");
var axios_1 = require("axios");
var usePromise_1 = require("./usePromise");
var setGlobals_1 = require("./setGlobals");
/**
* This hook consumes an API when calling the handler function.
* @param props Initial options
* @returns [state, handler, resetState, cancelFetch]
* @example
* ```
const [state, handler, resetState, cancelFetch ] = useLazyFetch({
url: 'your-endpoint-url',
initialData: {},
request: { headers: { example: 'test'} }
onCancel: () => {},
onComplete: (data, err) => {},
onFail: (err) => {},
onSuccess: (data) => {},
});
```
* @see https://www.npmjs.com/package/@anb98/react-hooks#useLazyFetch
*/
var useLazyFetch = function (props) {
var controller = React.useRef();
var _a = props || {}, _b = _a.url, initialUrl = _b === void 0 ? '' : _b, _c = _a.request, defaultRequest = _c === void 0 ? {} : _c, _d = _a.onCancel, onCancel = _d === void 0 ? function () { } : _d, _e = _a.onComplete, onComplete = _e === void 0 ? function () { } : _e;
var promise = function (request) {
if (request === void 0) { request = {}; }
controller.current = new AbortController();
var defaultWithCredentials = (defaultRequest === null || defaultRequest === void 0 ? void 0 : defaultRequest.withCredentials) || setGlobals_1.globals.withCredentials;
var url = request.url || initialUrl;
request.url = setGlobals_1.globals.baseURL ? "".concat(setGlobals_1.globals.baseURL, "/").concat(url) : url;
request.headers = __assign(__assign(__assign({}, setGlobals_1.globals.headers), defaultRequest.headers), request.headers);
request.withCredentials = defaultWithCredentials;
request.method = request.method || defaultRequest.method || 'GET';
request.signal = controller.current.signal;
return (0, axios_1.default)(request).then(function (_a) {
var data = _a.data;
return data;
});
};
var cancelFetch = function () {
if (controller.current) {
controller.current.abort();
onCancel();
}
};
var _f = (0, usePromise_1.default)(promise, __assign(__assign({}, props), { initialData: props === null || props === void 0 ? void 0 : props.initialData, onUnmount: cancelFetch, onComplete: function (data, err) {
controller.current = undefined;
onComplete(data, err);
} })), state = _f[0], fetchData = _f[1], resetState = _f[2];
return [state, fetchData, resetState, cancelFetch];
};
exports.default = useLazyFetch;
//# sourceMappingURL=useLazyFetch.js.map