Home > OS >  how to run two functions in onChange - React
how to run two functions in onChange - React

Time:09-06

Iam trying to create a 2 password fields and want to check if the 2 passwords are same and if they are it should enable the signup button.

const [passwordOne, setPasswordOne] = useState("");
const [passwordTwo, setPasswordTwo] = useState("");
const [disabled, setDisabled] = useState(true);

function checkPassword(input1, input2) {
    if (input1 === input2) {
      setDisabled(false);
      setOutput("");
    } else {
      setDisabled(true);
      setOutput("Passwords do not match");
    }
}

<input
  onChange={(e) => {
    setPasswordOne(e.target.value);    
    checkPassword(passwordOne, passwordTwo)}}
/>
<input
  onChange={(e) => {
    setPasswordTwo(e.target.value);    
    checkPassword(passwordOne, passwordTwo)}}
/>
<button disabled={disabled}>Register</button>

CodePudding user response:

You're not using the value of the latest passwords in your check.

The calls should be:

checkPassword(e.target.value, passwordTwo)
// and
checkPassword(passwordOne, e.target.value)

Consider simplifying the state:

const [passwordOne, setPasswordOne] = useState("");
const [passwordTwo, setPasswordTwo] = useState("");

const isPasswordFilled = passwordOne !== "";
const arePasswordsSame = isPasswordFilled && passwordOne === passwordTwo;

return <>
    <input onChange={(e) => setPasswordOne(e.target.value) />
    <input onChange={(e) => setPasswordTwo(e.target.value) />
    {isPasswordFilled === true && arePasswordsSame === false && <p>Passwords do not match</p>}
    <button disabled={isPasswordFilled === false || arePasswordsSame 
 === false}>Register</button>
</>;

CodePudding user response:

const [passwordOne, setPasswordOne] = useState("");
const [passwordTwo, setPasswordTwo] = useState("");
const [disabled, setDisabled] = useState(true);
const [output, setOutput] = useState("");

function checkPassword(input1, input2) {
    if (input1 === input2) {
      setDisabled(false);
      setOutput("");
    } else {
      setDisabled(true);
      setOutput("Passwords do not match");
    }
}

<input
  onChange={(e) => {
    setPasswordOne(e.target.value);    
    checkPassword(e.target.value, passwordTwo)}}
/>
<input
  onChange={(e) => {
    setPasswordTwo(e.target.value);    
    checkPassword(passwordOne, e.target.value)}}
/>
<p>{output}</p>
<button disabled={disabled}>Register</button>

You are sending state's value when it didn't set yet. So, if you can send current parameter, it works well.

  • Related