react-simple-api
Version:
Create and cache API requests and responses
165 lines • 8.76 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);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
import { useCallback, useEffect, useState } from 'react';
import { useApiContext } from './CacheContext';
import { areObjectsEqual, createRequest, normalizeError } from './utils';
var useApi = function (_a) {
var apiId = _a.apiId, apiUrl = _a.apiUrl, method = _a.method, data = _a.data, _b = _a.headers, headers = _b === void 0 ? {} : _b, cacheExpiry = _a.cacheExpiry, retry = _a.retry, onSuccess = _a.onSuccess, onError = _a.onError, pollInterval = _a.pollInterval, _c = _a.enabled, enabled = _c === void 0 ? true : _c;
var _d = useApiContext(), getCache = _d.getCache, setCache = _d.setCache, baseApiUrl = _d.baseApiUrl;
var retryTimes = retry || 0;
var initialErrorData = {
error: undefined,
isError: false,
};
var finalUrl = baseApiUrl ? baseApiUrl + apiUrl : apiUrl;
var apiIdentifier = apiId !== null && apiId !== void 0 ? apiId : JSON.stringify({ finalUrl: finalUrl, method: method, data: data });
var _e = useState(undefined), responseData = _e[0], setResponseData = _e[1];
var _f = useState(initialErrorData), errorData = _f[0], setErrorData = _f[1];
var _g = useState(true), isLoading = _g[0], setIsLoading = _g[1];
var _h = useState(true), isFetching = _h[0], setIsFetching = _h[1];
var _j = useState(false), isRetrying = _j[0], setIsRetrying = _j[1];
var _k = useState(false), cached = _k[0], setCached = _k[1];
var isCacheOutdated = function (cachedData, newResponseData) {
return !areObjectsEqual(cachedData, newResponseData);
};
var triggerAPI = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () {
var cachedResponse, response, responseText, responseData_1, error_1, normalError;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!enabled)
return [2 /*return*/];
setErrorData(initialErrorData);
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 5]);
cachedResponse = getCache(apiIdentifier);
if (cachedResponse) {
// return the cached response immediately
setResponseData(cachedResponse);
setIsLoading(false);
if (process.env.NODE_ENV !== 'production') {
setCached(true);
}
}
return [4 /*yield*/, createRequest({
apiUrl: finalUrl,
requestInfo: {
method: method,
body: JSON.stringify(data),
headers: headers,
},
})];
case 2:
response = _a.sent();
return [4 /*yield*/, response.text()];
case 3:
responseText = _a.sent();
responseData_1 = responseText && responseText.length > 0 ? JSON.parse(responseText) : {};
// if API fails, throw error
if (!response.ok) {
throw responseData_1;
}
onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(responseData_1);
setIsLoading(false);
setIsFetching(false);
setIsRetrying(false);
// compare the old cached data vs the new data
// if the cached data is old, replace it with the new response data
if (isCacheOutdated(cachedResponse, responseData_1)) {
setResponseData(responseData_1);
setCache(apiIdentifier, responseData_1, cacheExpiry);
}
return [3 /*break*/, 5];
case 4:
error_1 = _a.sent();
// if retry is specified, trigger the API call again, until retryTimes is 0
if (retryTimes && retryTimes > 0) {
retryTimes--;
setIsRetrying(true);
triggerAPI();
}
else {
normalError = normalizeError(error_1);
onError === null || onError === void 0 ? void 0 : onError(normalError);
setErrorData({
error: normalError,
isError: true,
});
setIsLoading(false);
setIsFetching(false);
setIsRetrying(false);
}
return [3 /*break*/, 5];
case 5: return [2 /*return*/];
}
});
}); }, [enabled, apiIdentifier]);
useEffect(function () {
if (enabled) {
triggerAPI();
}
}, [apiIdentifier, enabled, triggerAPI]);
useEffect(function () {
if (pollInterval && pollInterval > 0 && enabled) {
var interval_1 = setInterval(triggerAPI, pollInterval);
return function () { return clearInterval(interval_1); };
}
return;
}, [pollInterval, enabled, triggerAPI]);
var refetchAPI = useCallback(function () {
triggerAPI();
}, [triggerAPI]);
return __assign({ data: responseData, isLoading: isLoading, isFetching: isFetching, isRetrying: isRetrying, error: errorData.error, isError: errorData.isError, triggerApi: refetchAPI }, (process.env.NODE_ENV !== 'production'
? {
cached: cached,
}
: {}));
};
export { useApi };
//# sourceMappingURL=useApi.js.map