@anb98/react-hooks
Version:
Custom hooks for react
66 lines • 3.21 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 useLazyFetch_1 = require("./useLazyFetch");
var CacheContext_1 = require("./CacheContext");
/**
* This hooks allow to cache results from request previously fetched.
* To use this hooks you first need to implement CacheProvider.
* @param {string} url URL to request
* @param props Initial options
* @example
* ```
const [state, fetchHandler, resetState ] = useLazyFetchCache({
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#useFetchCache-and-useLazyFetchCache
*/
var useLazyFetchCache = function (props) {
var _a = props || {}, _b = _a.onSuccess, onSuccess = _b === void 0 ? function () { } : _b, _c = _a.onComplete, onComplete = _c === void 0 ? function () { } : _c;
var _d = React.useContext(CacheContext_1.CacheContext), stateCache = _d.result, setResult = _d.setResult;
var stringRequest = React.useRef('');
var _e = React.useState(props === null || props === void 0 ? void 0 : props.initialData), resultCache = _e[0], setResultCache = _e[1];
var setCache = function (data) {
setResult(stringRequest.current, data);
setResultCache(data);
onSuccess(data);
};
var _f = (0, useLazyFetch_1.default)(__assign(__assign({}, props), { onSuccess: setCache })), stateApi = _f[0], fetchData = _f[1], resetState = _f[2], cancelFetch = _f[3];
var _g = React.useState(stateApi), state = _g[0], setState = _g[1];
React.useEffect(function () { setState(stateApi); }, [stateApi]);
var verifyCache = function (request, _a) {
var _b = _a === void 0 ? {} : _a, refresh = _b.refresh;
var stringifyRequest = JSON.stringify(request || __assign(__assign({}, props === null || props === void 0 ? void 0 : props.request), { url: props === null || props === void 0 ? void 0 : props.url }));
if (!refresh && stateCache[stringifyRequest]) {
setResultCache(stateCache[stringifyRequest]);
setState(function (prev) { return (__assign(__assign({}, prev), { status: 'resolved', isSuccess: true })); });
onSuccess(stateCache[stringifyRequest]);
onComplete(stateCache[stringifyRequest], null);
}
else {
stringRequest.current = stringifyRequest;
fetchData(request);
}
};
return [__assign(__assign({}, state), { data: resultCache }), verifyCache, resetState, cancelFetch];
};
exports.default = useLazyFetchCache;
//# sourceMappingURL=useLazyFetchCache.js.map