Reputation: 155
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
Upvotes: 0
Views: 1371
Reputation: 370659
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);
Upvotes: 1