Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.0 kB
2
Indexable
Never
import React, { useState, useEffect, ChangeEvent, FormEvent } from 'react';
import { useNavigate } from 'react-router-dom';

function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [isButtonDisabled, setIsButtonDisabled] = useState(true);

  const navigate = useNavigate();

  const handleChangeEmail = (event: ChangeEvent<HTMLInputElement>) => {
    const { value } = event.target;
    setEmail(value);
  };

  const handleChangePassword = (event: ChangeEvent<HTMLInputElement>) => {
    const { value } = event.target;
    setPassword(value);
  };

  useEffect(() => {
    // Verificar se o email possui um @ e a senha tem pelo menos 6 caracteres
    const emailPattern = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
    const isEmailValid = emailPattern.test(email);
    const isPasswordValid = password.length > 6;

    if (isEmailValid && isPasswordValid) {
      setIsButtonDisabled(false);
    } else {
      setIsButtonDisabled(true);
    }
  }, [email, password]);

  const handleSubmit = (event: FormEvent) => {
    event.preventDefault();
    // salvar email no localStorage na chave 'user' no formato { email: email-da-pessoa }
    localStorage.setItem('user', JSON.stringify({ email }));
    // redirecionar para a rota /meals
    navigate('/meals');
  };

  return (
    <section>
      <div>
        <form onSubmit={ handleSubmit }>
          <input
            type="text"
            value={ email }
            onChange={ handleChangeEmail }
            data-testid="email-input"
          />
          <input
            value={ password }
            onChange={ handleChangePassword }
            type="password"
            data-testid="password-input"
          />
          <button
            data-testid="login-submit-btn"
            disabled={ isButtonDisabled }
          >
            Enter

          </button>
        </form>
      </div>
    </section>
  );
}

export default Login;
Leave a Comment