Home > Mobile >  The state of usestate is not updated for all error for the forms
The state of usestate is not updated for all error for the forms

Time:09-19

How can I update the state for all of the errors?

for example, I have to validate the fields name and last name:

const handleSubmit = () => {
    const { name, lastName } = fields
    let existError = false

    if (!verify(name)) {
      existError = true
      setError({ ...error, ['name']: 'name is bad' })
    }

    if (!verify(lastName)) {
      existError = true
      setError({ ...error, ['lastName']: 'lastname is bad' })

    }

    if (!existError) {
     ...
    }
  }
  console.log('ERROR', error)

I can only see this error

ERROR {lastName: 'lastname is bad'} i am waiting this result:

{name: 'name is bad', lastName: 'lastname is bad'}

CodePudding user response:

The value of error within your handleSubmit function won't update until the next render, so when you set lastName:

setError({ ...error, ['lastName']: 'lastname is bad' })

error still doesn't have the name property and you end up overwriting the name update with the lastName update.

You're effectively doing this:

const error = {
  foo: 123
}

let state = {
  ...error,
  name: 'name is bad'
}

console.log(state); // { foo: 123, name: 'name is bad' }

state = {
 ...error, // still doesn't contain 'name'
 lastName: 'last name is bad'
}

console.log(state); // { foo: 123, lastName: 'last name is bad' }

You could avoid this by collecting your errors in a separate object and doing a single state update that includes all of them.

let errors = {};

if(!verify(name)) {
  errors.name = 'name is bad'
}

if(!verify(lastName)) {
  errors.lastName = 'last name is bad'
}

setError({ ...error, ...errors });

CodePudding user response:

Try this instead:

if(!verify(name)){
    setState(prevError => { 
       return {...prevError, name: 'name is bad'}
    });
}

if(!verify(lastName)){
    setState(prevError => { 
       return {...prevError, lastName: 'lastName is bad'}
    });
}

The value error wasn't updated after the first if block, due to asynchronous reasons. When you used the error value in the second if block, it still used it's orignal value.

  • Related