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
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!