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`)}
  };

1
  • Are you using react hooks or class based approach? Commented Nov 18, 2020 at 14:33

2 Answers 2

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])
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.