简体   繁体   中英

How to update hook state in a loop?

I have a state and I am updating it in a loop. I have an issue where the state that was previously updated did not have enough time to update so I get undefined values.

Example:

const [errors, setErrors] = useState({})

On every second item I am changing the email prop but want to keep the password prop as is.

   for (let i = 0; i < res.length; i += 1) {
      if (i % 2) setErrors({ email: test${i}, password: errors.password });
      else setErrors({ email: errors.email, password: test2${i} });
      console.log('err', errors);
    }

The result ends up giving me

email:test1

and

password:undefined

Is it possible to update state like this or am I going on about it the wrong way?

Use the updater version of useState and spread all properties overwriting email

if (i % 2) setErrors(prevErros =>({ ...prevErros, email: test${i}})

Can you set once at end? You shouldn't be calling the same setState function multiple times in one hook

let currentEmail = null;
let currentPassword = null;

for (let i = 0; i < res.length; i += 1) {
  if (i % 2) {
    currentEmail = `test_${i}`;
  } else {
    currentPassword = `test2_${i}`;
  }
}

setErrors({ email: currentEmail, password: currentPassword });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM