import React, { useState } from 'react'; import './Login.scss'; import authServices from '../../services/authServices'; import FormError from '../FormError/FormError'; const Login = (props) => { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const minimumPasswordLength = 8; const errorDispatchAction = { type: 'ERR', message: 'AUTH_ERROR' } const validateLoginForm = next => { if (password.length < minimumPasswordLength) { return props.dispatch({ ...errorDispatchAction, body: { authError: 'This password is invalid'} }) } if (!/^[\w\d_.-]+$/.test(username)) { return props.dispatch({ ...errorDispatchAction, body: { authError: "This username is invalid"} }) } next(); } const postLoginForm = async () => { const loginResponse = await authServices.loginService({ username, password }) const parsedResponse = JSON.parse(loginResponse); if (parsedResponse.errors) { const authError = parsedResponse.errors return props.dispatch({ ...errorDispatchAction, body: { authError } }) } return props.dispatch({ type: 'AUTH', message: 'LOGIN', body: parsedResponse }) } const handleSubmit = e => { e.preventDefault(); validateLoginForm(postLoginForm); } const formError = errors => { if(!errors) return <>; if (errors.auth) { return } } return (
{formError(props.state.errors)}
handleSubmit(e)} > setUsername(e.target.value)} default="username" /> setPassword(e.target.value)} default="" />
); } export default Login;