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

141
Visualizações
I have to show an error message whenever a user enters a string that doesn't match any item in the user array

When I use else if to show an error message, it says "wrong username" even when the username is correct but the password is incorrect. Except for the last username in the "user" array.

But when I remove the else if it does nothing when a user enters the wrong username.

I think the for loop is creating that problem. Am I using the wrong loop for the wrong purpose? what should I do?

Codesandbox link https://codesandbox.io/s/nervous-moser-ybvwb3?file=/src/App.js:1066-1203

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

First off, you shouldn't have your credentials hard coded to the front-end like that. Anyone could just read the code and get in.

That being said, you need to break the loop when the username is found:

if (usernameState === user[i]) {
  if (passwordState === pass[i]) {
    setLoginState(true);
    setMessageState("Login successful.");
  } else if (passwordState === "") {
    setMessageState("Enter password.");
    passwordinput.current.focus();
  } else {
    setMessageState("Wrong password.");
    passwordinput.current.focus();
  }
  break;
}

Otherwise you will continue to process each username since no matches were found. I really wouldn't use a for loop for this at all. You should do your check for an empty string first, then find if the username is in your array, then if it is check the password. But again you really shouldn't embed the credentials in your front-end code!

about 4 years ago · Juan Pablo Isaza 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