Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!