@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
66 lines (65 loc) • 2.64 kB
JavaScript
import { __awaiter, __generator } from "tslib";
import { handleRespError } from '@open-tender/utils';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
var useBarcode = function (api) {
var isAborted = useRef(false);
var _a = useState(null), code = _a[0], setCode = _a[1];
var _b = useState(null), error = _b[0], setError = _b[1];
useEffect(function () {
return function () {
isAborted.current = true;
};
}, []);
var read = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () {
var response, err_1, detail;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, api.getBarcodeRead()];
case 1:
response = _a.sent();
if (!isAborted.current) {
if (response) {
setCode(response.data);
}
else {
setError('Read timed out');
}
}
return [3 /*break*/, 3];
case 2:
err_1 = _a.sent();
if (!isAborted.current) {
detail = handleRespError(err_1).detail;
setError(detail || 'Unknown error');
}
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); }, [api]);
var cancel = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () {
var err_2, detail;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, api.postBarcodeCancel()];
case 1:
_a.sent();
return [3 /*break*/, 3];
case 2:
err_2 = _a.sent();
if (!isAborted.current) {
detail = handleRespError(err_2).detail;
setError(detail || 'Unknown error');
}
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); }, [api]);
return useMemo(function () { return ({ code: code, error: error, read: read, cancel: cancel }); }, [code, error, read, cancel]);
};
export default useBarcode;