Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'value')

I'm getting this error:

Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'value')

I need to get the values from the login form (inputs: username and password) but when I submit the form the error appears.

AuthContext.js

let loginUser = async (e) => {
  e.preventDefault();
  let response = await fetch(
    "https://estudio-ghibli-2022.herokuapp.com/login",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        username: e.target.username.value,
        password: e.target.password.value,
      }),
    }
  );
  let data = await response.json();
  console.log("data: ", data);
};

let contextData = {
  loginUser: loginUser,
};

This is my login page:

const Login = () => {
  const { loginUser } = useContext(AuthContext);

  return (
    <FormInner>
      <Title>Studio Ghibli Tracker</Title>
      <Subtitle>Login</Subtitle>
      <Container>
        <label>Email</label>
        <input name="username" placeholder="example@mail.com" />
        <img src={userLogo} alt="user logo" />
      </Container>
      <Container>
        <label>Password</label>
        <input name="password" placeholder="******" />
        <img src={key} alt="key logo" />
      </Container>

      <LoginBtn type="button" onClick={loginUser}>
        Login
      </LoginBtn>
    </FormInner>
  );
};
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Your loginUser function is attached to the <LoginBtn> click event. Assuming that component passes some kind of Event to the handler, it's probably an event triggered by a <button> (or similar) which is what is assigned to e.target. There won't be any username property.

What you should be doing here is have your username and password inputs be controlled components with their value tied to state

const [username, setUsername] = useState("");
const [password, setPassword] = useState("");

and

<input
  value={username}
  placeholder="example@mail.com"
  onChange={(e) => setUsername(e.target.value)}
/>
<input
  type="password"
  value={password}
  placeholder="******"
  onChange={(e) => setPassword(e.target.value)}
/>

Your loginUser context function should accept username and password strings instead of an event

const loginUser = async (username, password) => {
  const response = await fetch(
    "https://estudio-ghibli-2022.herokuapp.com/login",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ username, password }),
    }
  );

  // don't forget to check for errors
  if (!response.ok) {
    throw response;
  }

  const data = await response.json();
  console.log("loginUser data:", data);
  // now do something with data ¯\_(ツ)_/¯
};

and

<LoginBtn
  type="button"
  onClick={(e) => { e.preventDefault(); loginUser(username, password); }
>Login</LoginBtn>
about 4 years ago · Santiago Trujillo Relatório

0

The problem is that you are trying to access the value of username and password fields from non existing properties in your loginUser function:

body: JSON.stringify({
  username: e.target.username.value,
  password: e.target.password.value,
})

I'm assuming that the param "e" is a React.MouseEvent because you are assigning loginUser as the handler of onClick event of the <LoginBtn> component:

<LoginBtn type="button"
          onClick={loginUser}>
  Login
</LoginBtn>

So unless you have a custom implementation in that component that somehow extracts this data from the form, there's a good chance that e.target points to an element that is not relevant for you to get this information.

So you could use Phil's suggested approach in the other answer using controlled components for the inputs to fix the issue or you could also set your handler to an onSubmit event of the form containing this elements and extract the information using FormData like this:

let loginUser = async (e) => {
  ...
  const formData = new FormData(e.target);
  const { username, password } = Object.fromEntries(formData.entries());

  let response = await fetch(..., {
    ...
    body: JSON.stringify({ username, password }),
  );
  ...
};

Assuming that <FormInner> has onSubmit event:

<FormInner onSubmit={loginUser}>
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda