4

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?

2

2 Answers 2

3

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

if (i % 2) setErrors(prevErros =>({ ...prevErros, email: test${i}}) 
Sign up to request clarification or add additional context in comments.

Comments

0

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

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.