UNPKG

react-discord-login

Version:

A React component for easy integration of 'Sign in with Discord' functionality into web applications

61 lines 2.66 kB
import { __assign, __awaiter, __generator, __rest } from "tslib"; import { useCallback, useEffect, useState } from 'react'; import { fetchUser, generateUrl, getCallbackResponse, normalizeDiscordConfig, shouldHandleCallback } from './utils'; var useDiscordLogin = function (_a) { var onSuccess = _a.onSuccess, onFailure = _a.onFailure, options = __rest(_a, ["onSuccess", "onFailure"]); var _b = useState(false), isLoading = _b[0], setLoading = _b[1]; var discordConfig = normalizeDiscordConfig(options); var handleCallback = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () { var _a, type, error, token, code, url, user; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = getCallbackResponse(), type = _a.type, error = _a.error, token = _a.token, code = _a.code; if (type !== null) { setLoading(true); url = new URL(window.location.origin); url.search = ''; url.hash = ''; history.replaceState(null, '', url); } if (!(error && onFailure)) return [3 /*break*/, 2]; return [4 /*yield*/, onFailure(error)]; case 1: _b.sent(); _b.label = 2; case 2: if (!(code && onSuccess)) return [3 /*break*/, 4]; return [4 /*yield*/, onSuccess(code)]; case 3: _b.sent(); _b.label = 4; case 4: if (!(token && onSuccess)) return [3 /*break*/, 7]; return [4 /*yield*/, fetchUser(token)]; case 5: user = _b.sent(); return [4 /*yield*/, onSuccess(__assign(__assign({}, token), { user: user }))]; case 6: _b.sent(); _b.label = 7; case 7: if (type !== null) { setLoading(false); } return [2 /*return*/]; } }); }); }, []); useEffect(function () { if (shouldHandleCallback()) { handleCallback().catch(console.error); } }, []); var buildUrl = function () { return generateUrl(discordConfig); }; return { buildUrl: buildUrl, isLoading: isLoading, }; }; export default useDiscordLogin; //# sourceMappingURL=useDiscordLogin.js.map