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

63 lines (62 loc) 2.86 kB
import { __awaiter, __generator, __spreadArray } from "tslib"; import { handleRespError } from '@open-tender/utils'; import { useState, useEffect, useRef, useCallback, useMemo } from 'react'; var useEmployee = function (api) { var isAborted = useRef(false); var _a = useState(null), employee = _a[0], setEmployee = _a[1]; var _b = useState(null), error = _b[0], setError = _b[1]; useEffect(function () { return function () { isAborted.current = true; }; }, []); var fetch = useCallback(function (identifier_1) { var args_1 = []; for (var _i = 1; _i < arguments.length; _i++) { args_1[_i - 1] = arguments[_i]; } return __awaiter(void 0, __spreadArray([identifier_1], args_1, true), void 0, function (identifier, withPunches) { var employee_1, employee_id, response, err_1, detail; if (withPunches === void 0) { withPunches = false; } return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 4, , 5]); return [4 /*yield*/, api.getEmployee(identifier)]; case 1: employee_1 = _a.sent(); if (!withPunches) return [3 /*break*/, 3]; employee_id = employee_1.employee_id; return [4 /*yield*/, api.getTimePunchesReport(null, employee_id)]; case 2: response = _a.sent(); if (response.length) employee_1 = response[0]; _a.label = 3; case 3: if (!isAborted.current) { setEmployee(employee_1); } return [3 /*break*/, 5]; case 4: err_1 = _a.sent(); if (!isAborted.current) { detail = handleRespError(err_1).detail; if (detail === null || detail === void 0 ? void 0 : detail.includes('does not exist')) { detail = 'Employee not found. Please try again.'; } setError(detail || 'Unknown erorr'); } return [3 /*break*/, 5]; case 5: return [2 /*return*/]; } }); }); }, [api]); var reset = useCallback(function () { setEmployee(null); setError(null); }, []); return useMemo(function () { return ({ employee: employee, error: error, fetch: fetch, reset: reset }); }, [employee, error, fetch, reset]); }; export default useEmployee;