简体   繁体   中英

React Hooks: setState hook inside map function

Im currently wrestling with the async nature of setState with a form, my intended behaviour is that when the user clicks on the submitForm button it checks all the form values inside the state if that value is empty it then sets the errorState for that specific form element so that an error message appears

  const [values, setValues] = React.useState({
    firstName: '',
    lastName: '',
    id: '',
    city: '',
    emailAddress:'',
    mobileNumber: ''
  });

  const [errors, setError] = React.useState({
    firstName: false,
    lastName: false,
    id: false,
    city: false,
    emailAddress: false,
    mobileNumber: false
  })

  const submitForm = () => {
    const setErrorArray = Object.keys(values).map((key) => {
      if (values[key] === '') {
        setError({...errors, [key]: true })
      }
    });
  }

I believe the issue is due to setState being async, so after the.map is done it sets only the last value inside the errors object to be true (thus errors.mobileNumber = true). Instead of making all the values that match the condition to be true. The spread operator {...errors} is overwriting the values to the initial false value.Is there anyway to achieve that each key inside errors is set to true if the value inside the values array is empty??

Please any help will be greatly appreciated

I'd construct the whole new errors object at once by mapping the entries of the values, and then you can call setError with that object:

 const values = { firstName: 'first', lastName: 'last', id: '', city: '', }; const newErrors = Object.fromEntries( Object.entries(values).map( ([key, val]) => [key, val === ''] ) ); console.log(newErrors); // setError(newErrors);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM