UNPKG

@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.14 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var react_1 = require("react"); var SCAN_MAX_TIME_DIFF = 100; var useBarcodeUSB = function (listener) { var barcodeArray = (0, react_1.useRef)([]); var _a = (0, react_1.useState)(false), setCodeScanned = _a[1]; var _b = (0, react_1.useState)(null), error = _b[0], setError = _b[1]; var timer = (0, react_1.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 = (0, react_1.useCallback)(function () { return tslib_1.__awaiter(void 0, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) { listener.cancel(function () { return clearTimeout(timer === null || timer === void 0 ? void 0 : timer.current); }); return [2 /*return*/]; }); }); }, [listener]); var reset = (0, react_1.useCallback)(function () { return tslib_1.__awaiter(void 0, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) { cancel(); barcodeArray.current = []; setCodeScanned(false); setError(null); return [2 /*return*/]; }); }); }, [cancel]); (0, react_1.useEffect)(function () { return function () { reset(); }; }, [reset]); var read = function () { return tslib_1.__awaiter(void 0, void 0, void 0, function () { return tslib_1.__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 }; }; exports.default = useBarcodeUSB;