Home > Net >  How to combine useState and useEffect properly
How to combine useState and useEffect properly

Time:01-25

I want to compare 2 inputs value. The typical password/repeat password input in a form.

Using onChange react useState render the DOM but not immediately because I shopuld use useEffect.

But I'm not sure how to combine both. I'm conscious there is other answers replying something similar but I can't apply to this case.

This is my useSstate:

 const [user, setUser] = useState({
        username: '',
        password: '',
    });

This is my onInputChange function:

const onInputChange = (e) => {
        if ((e.target.id === 'password') === (e.target.id === 'confirmPassword')) {
            console.log('Match!')
        } else {
            console.log('DO NOT Match')
        }
        setUser({ ...user, [e.target.name]: e.target.value });
        console.log('User Updating values: ', user)
    }

This is the input (MUI textfield):

    <TextField
      id="password"
      name="password"
      label="Password"
      type="password"
      onChange={(e) => onInputChange(e)}
    />
                                                
<TextField
      id="confirmPassword"
      name="confirmPassword"
      label="Confirm password"
      type="password"
      onChange={(e) => onInputChange(e)}
 />

Could you help me with this, please?

CodePudding user response:

You can use the useEffect hook to listen for changes in the user state and compare the values of the password and confirmPassword fields. Here is an example of how you can combine useState and useEffect to accomplish this:

const [user, setUser] = useState({
  username: '',
  password: '',
});

const onInputChange = (e) => {
  setUser({ ...user, [e.target.name]: e.target.value });
};

useEffect(() => {
  if (user.password === user.confirmPassword) {
    console.log('Passwords match!');
  } else {
    console.log('Passwords do not match!');
  }
}, [user.password, user.confirmPassword]);

In this example, useEffect is listening for changes in the user.password and user.confirmPassword fields, and it will run the comparison logic inside the callback function whenever either of these fields change. Also, you can set a condition to compare the values of password and confirmPassword in your onInputChange function and set an error message or a state for that.

const onInputChange = (e) => {
  setUser({ ...user, [e.target.name]: e.target.value });
}

You can also make use of the name attribute instead of the id attribute in the textfields.

<TextField
  name="password"
  label="Password"
  type="password"
  onChange={(e) => onInputChange(e)}
/>

<TextField
  name="confirmPassword"
  label="Confirm password"
  type="password"
  onChange={(e) => onInputChange(e)}
/>

It's important to note that useEffect will run on every render, making the comparison logic inside it to run every time the component re-renders.

Also, please take care of the dependencies of the useEffect. If you don't provide the correct dependencies, it might create an infinite loop.

CodePudding user response:

Here you can find how it works

CodeSandBox

This is not best practice because you should match password on submit or on blur event trigger on each input.

Ask me if you need furthur help !

Thank You.

  • Related