import React, { FunctionComponent, useState } from 'react'; import { useHistory } from 'react-router-dom'; import AuthenticationService from '../services/authentication-service'; type Field = { value?: any, error?: string, isValid?: boolean }; type Form = { username: Field, password: Field } const Login: FunctionComponent = () => { const history = useHistory(); const [form, setForm] = useState
({ username: { value: '' }, password: { value: '' }, }); const [message, setMessage] = useState('Vous êtes déconnecté. (pikachu / pikachu)'); const handleInputChange = (e: React.ChangeEvent): void => { const fieldName: string = e.target.name; const fieldValue: string = e.target.value; const newField: Field = { [fieldName]: { value: fieldValue } }; setForm({ ...form, ...newField}); } const validateForm = () => { let newForm: Form = form; // Validator username if(form.username.value.length < 3) { const errorMsg: string = 'Votre prénom doit faire au moins 3 caractères de long.'; const newField: Field = { value: form.username.value, error: errorMsg, isValid: false }; newForm = { ...newForm, ...{ username: newField } }; } else { const newField: Field = { value: form.username.value, error: '', isValid: true }; newForm = { ...newForm, ...{ username: newField } }; } // Validator password if(form.password.value.length < 6) { const errorMsg: string = 'Votre mot de passe doit faire au moins 6 caractères de long.'; const newField: Field = {value: form.password.value, error: errorMsg, isValid: false}; newForm = { ...newForm, ...{ password: newField } }; } else { const newField: Field = { value: form.password.value, error: '', isValid: true }; newForm = { ...newForm, ...{ password: newField } }; } setForm(newForm); return newForm.username.isValid && newForm.password.isValid; } const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); const isFormValid = validateForm(); if(isFormValid) { setMessage('👉 Tentative de connexion en cours ...'); AuthenticationService.login(form.username.value, form.password.value).then(isAuthenticated => { if(!isAuthenticated) { setMessage('🔐 Identifiant ou mot de passe incorrect.'); return; } history.push('/pokemons'); }); } } return ( handleSubmit(e)}>
{/* Form message */} {message &&
{message}
} {/* Field username */}
handleInputChange(e)}> {/* error */} {form.username.error &&
{form.username.error}
}
{/* Field password */}
handleInputChange(e)}> {/* error */} {form.password.error &&
{form.password.error}
}
{/* Submit button */}
); }; export default Login;