import React, { useState } from 'react'; import { useHistory } from 'react-router-dom'; import { Box, Grid, TextField, Button, Typography, Paper, CircularProgress } from '@material-ui/core'; import { makeStyles, createStyles, Theme } from '@material-ui/core/styles'; import AuthService from './AuthService'; export default function Auth(props: any) { props.onAuthenticated(); const history = useHistory(); const classes = useStyles(); const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [showError, setShowError] = useState(false); const [errorMessage, setErrorMessage] = useState(''); const [isLoggingIn, setIsLoggingIn] = useState(false); const onUsernameChanged = (event: any) => { setUsername(event.target.value); setShowError(false); setErrorMessage(''); }; const onPasswordChanged = (event: any) => { setPassword(event.target.value); setShowError(false); setErrorMessage(''); }; const onPasswordKeyPress = (event: any) => { if (event.key === 'Enter') { onLoginClicked(); } }; const onLoginClicked = () => { if (!username) { setShowError(true); setErrorMessage('Username required'); return; } if (!password) { setShowError(true); setErrorMessage('Password required'); return; } setIsLoggingIn(true); AuthService.login(username, password) .then(() => { setIsLoggingIn(false); props.onAuthenticated(); history.push('/'); }).catch(() => { setShowError(true); setIsLoggingIn(false); setErrorMessage('Invalid credentials'); }); }; const renderErrorLabel = () => { return showError ? {errorMessage} : ; }; const renderLoginButton = () => { return isLoggingIn ? : }; return ( Sign in {renderErrorLabel()} {renderLoginButton()} ); }; const useStyles = makeStyles((theme: Theme) => createStyles({ root: { display: 'flex', alignItems: 'center', justifyContent: 'center', minWidth: 400, minHeight: 600, }, container: { padding: 40, flexDirection: "column", justifyContent: "space-around", alignItems: "center", }, paper: { borderRadius: 15, }, button: { justifyContent: "center", }, error: { color: "red", } }), );