Home > Software design >  Set array items in react js state
Set array items in react js state

Time:11-22

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:

enter image description here

is there anyone face to this problem?

CodePudding user response:

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}))
  • Related