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

51 lines (50 loc) 2.06 kB
import { __awaiter, __generator } from "tslib"; import { handleRespError } from '@open-tender/utils'; import { useState, useEffect, useRef, useCallback, useMemo } from 'react'; var useGiftCardBalance = function (api) { var isAborted = useRef(false); var _a = useState(null), giftCard = _a[0], setGiftCard = _a[1]; var _b = useState('idle'), loading = _b[0], setLoading = _b[1]; var _c = useState(null), error = _c[0], setError = _c[1]; useEffect(function () { return function () { isAborted.current = true; }; }, []); var fetch = useCallback(function (code) { return __awaiter(void 0, void 0, void 0, function () { var giftCard_1, err_1, detail; return __generator(this, function (_a) { switch (_a.label) { case 0: setLoading('pending'); _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, api.getGiftCardBalance(code)]; case 2: giftCard_1 = _a.sent(); if (!isAborted.current) { setGiftCard(giftCard_1); } return [3 /*break*/, 4]; case 3: err_1 = _a.sent(); if (!isAborted.current) { detail = handleRespError(err_1).detail; setError(detail || 'Unknown error'); } return [3 /*break*/, 4]; case 4: setLoading('idle'); return [2 /*return*/]; } }); }); }, [api]); var reset = useCallback(function () { setGiftCard(null); setLoading('idle'); setError(null); }, []); return useMemo(function () { return ({ giftCard: giftCard, loading: loading, error: error, fetch: fetch, reset: reset }); }, [giftCard, loading, error, fetch, reset]); }; export default useGiftCardBalance;