0

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?

3
  • First don't provide the code snippet as image, instead provide them as real code snippet. Next provide the data that you receive from emptyInputs .. Commented Nov 22, 2021 at 6:33
  • Here you are. I changed my answer Commented Nov 22, 2021 at 6:45
  • Could you provide a emptyInputs data Commented Nov 22, 2021 at 9:42

1 Answer 1

1

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}))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.