Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set array items in react js state

Here I have a state which its initial value is an empty obj.

const [error, setError] = useState({});

In the next step, I’m checking if there is vacant input, set its key to the error state :

if (emptyInputs.length) {
            emptyInputs.forEach(key => setError({ ...error, [key]: true }));

but only one of the empty inputs name sets to my error state:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

is there anyone face to this problem?

>Solution :

When you are looping through the emptyInput for each item you are assigning a new object to the error state because of that you are losing the previous state/key, first of all, you will have to copy the previous object to keep its values and then assign a new key like so.

This is a recommended way to set the state if your state depends on the previous state.

emptyInputs.forEach(key => setError(prevState => ({...prevState, [key]: true})))

This is not a recommended way to update the state like this because this way doesn’t guarantee getting the latest state for each update if your state changes very frequently.

emptyInputs.forEach(key => setError({...error, [key]: true}))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading