@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
51 lines (50 loc) • 1.97 kB
JavaScript
import { __awaiter, __generator } from "tslib";
import { useCallback, useEffect, useRef, useState } from 'react';
var SCAN_MAX_TIME_DIFF = 100;
var useBarcodeUSB = function (listener) {
var barcodeArray = useRef([]);
var _a = useState(false), setCodeScanned = _a[1];
var _b = useState(null), error = _b[0], setError = _b[1];
var timer = useRef(undefined);
var updateBarcode = function (data) {
barcodeArray.current.push(data.pressedKey);
clearTimeout(timer === null || timer === void 0 ? void 0 : timer.current);
timer.current = setTimeout(function () { return setCodeScanned(function (prev) { return !prev; }); }, SCAN_MAX_TIME_DIFF);
};
var cancel = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
listener.cancel(function () { return clearTimeout(timer === null || timer === void 0 ? void 0 : timer.current); });
return [2 /*return*/];
});
}); }, [listener]);
var reset = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
cancel();
barcodeArray.current = [];
setCodeScanned(false);
setError(null);
return [2 /*return*/];
});
}); }, [cancel]);
useEffect(function () {
return function () {
reset();
};
}, [reset]);
var read = function () { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
listener.read(updateBarcode);
return [2 /*return*/];
});
}); };
return {
code: barcodeArray.current.length > 0
? barcodeArray.current.join('').trim()
: null,
read: read,
cancel: cancel,
reset: reset,
error: error
};
};
export default useBarcodeUSB;