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

77 lines (76 loc) 3.02 kB
import { __awaiter, __generator } from "tslib"; import { handleRespError } from '@open-tender/utils'; import { useState, useEffect, useCallback, useRef, useMemo } from 'react'; var parseSwipeCard = function (data) { try { var parts = data.split('?'); var code = parts[0].slice(1); return code.length > 36 ? null : code; } catch (err) { return null; } }; var useCardSwipe = function (api, parse) { if (parse === void 0) { parse = true; } 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 data, err_1, detail; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, api.getCardRead()]; case 1: data = (_a.sent()).data; if (parse) data = parseSwipeCard(data); data ? setCode(data) : setError('Could not read card. Please try again.'); if (!isAborted.current) { data ? setCode(data) : setError('Could not read card. Please try again.'); } return [3 /*break*/, 3]; case 2: err_1 = _a.sent(); if (!isAborted.current) { detail = handleRespError(err_1).detail; setError(detail || 'Unknown erorr'); } return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }, [api, parse]); 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.postCardCancel()]; 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 erorr'); } 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 useCardSwipe;