0

There are 2 event handlers that handle passwords. The first inputPassword writes the value from its input to state the second inputPasswordRE writes the value of input and compares it to the value from inputPassword. Since setState works asynchronously, even if the same values are entered, the check fails, so how in inputPasswordRE its previous state is compared (When you enter in the password field - 12345 and in the re_password field - 12345, their values password === re_password will be false.). How to correctly write setState in inputPasswordRE so that did the comparison work correctly?

const inputPassword = (e) => {
    setState(({ ...state, password: e.target.value }));
  };
  const inputPasswordRE = (e) => {
    setState({ ..state, re_password: e.target.value });
    if (password === re_password) {
      alert(`SUCCESS`)
    } else {alert(`ERROR`)}
  };

Nik
  • 3
  • 1

2 Answers2

0

You're right, setState is updates state asynchronously, so it does not guaranty change immediately, you can use following approach to do your task.

Using Class based

const inputPasswordRE = (e) => {
   this.setState({ ..state, re_password: e.target.value }, (state) => {
      if (state.password === state.re_password) {
        alert(`SUCCESS`)
      } else {
        alert(`ERROR`)
      }
   });
  };

OR

You can also use `componentDidUpdate` as well.

Using React Hooks

If you're using react hooks, you can use useEffect to detect the changes and do your validations.

useEffect(() => {
 if (password === re_password) {
    // Do your stuff here
 }
}, [password, re_password])
Naren
  • 4,152
  • 3
  • 17
  • 28
0

You can use the following for class-based components.

componentDidUpdate(prevProps, prevState) {
  if (this.state.password === this.state.rePassword) {
    // passwords matched
  } else {
    // passwords didn't match
  }
}

You can also use function-based component with a useState hook. Check out the following code

import React, {useState, useEffect} from 'react'

export default function func() {
  const [password, setPassword] = useState('');
  const [rePassword, setRePassword] = useState('');
  
  useEffect(() => {
    if (password === rePassword){
      // passwords matched
    } else {
      // passwords don't match
    }
  })
  return (
    <div>
      <input type="text" name="password" type="password" onClick={(e) => setPassword(e.target.value)} />
      <input type="text" name="password" type="password" onClick={(e) => setRePassword(e.target.value)} />
    </div>
  );
}

This should work perfectly.

Comment if you wanna know anything else.

Pranta
  • 2,928
  • 7
  • 24
  • 37