@open-tender/store
Version:
A library of hooks, reducers, utility functions, and types for use with Open Tender applications that utilize our in-store POS API
53 lines (52 loc) • 2.21 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var utils_1 = require("@open-tender/utils");
var react_1 = require("react");
var useGiftCardBalance = function (api) {
var isAborted = (0, react_1.useRef)(false);
var _a = (0, react_1.useState)(null), giftCard = _a[0], setGiftCard = _a[1];
var _b = (0, react_1.useState)('idle'), loading = _b[0], setLoading = _b[1];
var _c = (0, react_1.useState)(null), error = _c[0], setError = _c[1];
(0, react_1.useEffect)(function () {
return function () {
isAborted.current = true;
};
}, []);
var fetch = (0, react_1.useCallback)(function (code) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
var giftCard_1, err_1, detail;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
setLoading('pending');
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, api.getGiftCardBalance(code)];
case 2:
giftCard_1 = _a.sent();
if (!isAborted.current) {
setGiftCard(giftCard_1);
}
return [3 /*break*/, 4];
case 3:
err_1 = _a.sent();
if (!isAborted.current) {
detail = (0, utils_1.handleRespError)(err_1).detail;
setError(detail || 'Unknown error');
}
return [3 /*break*/, 4];
case 4:
setLoading('idle');
return [2 /*return*/];
}
});
}); }, [api]);
var reset = (0, react_1.useCallback)(function () {
setGiftCard(null);
setLoading('idle');
setError(null);
}, []);
return (0, react_1.useMemo)(function () { return ({ giftCard: giftCard, loading: loading, error: error, fetch: fetch, reset: reset }); }, [giftCard, loading, error, fetch, reset]);
};
exports.default = useGiftCardBalance;