Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

140
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda