// login.tsx // Copyright (C) 2020 Dwayne Harris // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see . import React, { FC, useEffect } from 'react' import { useSelector, useDispatch } from 'react-redux' import { useHistory } from 'react-router' import { faIdCard } from '@fortawesome/free-solid-svg-icons' import { handleApiError } from '../../api/errors' import { authenticate } from '../../actions/authentication' import { showNotification } from '../../actions/notifications' import { getChecked, getAuthenticated } from '../../selectors/authentication' import { getFieldValue } from '../../selectors/forms' import { getIsFetching } from '../../selectors/requests' import { initForm, initField, setFieldNotification } from '../../actions/forms' import Title from '../../components/title' import Section from '../../components/section' import TextField from '../../components/controls/text-field' import PasswordField from '../../components/controls/password-field' import PrimaryButton from '../../components/controls/primary-button' import { AppState, RequestKey, NotificationType } from '../../types' const Login: FC = () => { const checked = useSelector(getChecked) const authenticated = useSelector(getAuthenticated) const name = useSelector(state => getFieldValue(state, 'name', '')) const password = useSelector(state => getFieldValue(state, 'password', '')) const authenticating = useSelector(state => getIsFetching(state, RequestKey.Authenticate)) const dispatch = useDispatch() const history = useHistory() useEffect(() => { if (checked && authenticated) history.push('/self') }, [checked, authenticated]) useEffect(() => { dispatch(initForm()) dispatch(initField('name', '', 'id')) dispatch(initField('password', '')) }, []) const handleAuthenticate = async () => { let invalid = false if (!name) { dispatch(setFieldNotification('name', NotificationType.Error, 'This is required')) invalid = true } if (!password) { dispatch(setFieldNotification('password', NotificationType.Error, 'This is required')) invalid = true } if (invalid) return try { const id = await dispatch(authenticate(name, password)) dispatch(showNotification(NotificationType.Welcome, `Welcome back ${id}!`)) history.push('/') } catch (err) { handleApiError(err, dispatch, history) } } return (
Log In to Flexor handleAuthenticate()} loading={authenticating} />
) } export default Login