Hello I have a question because I decided to use 'useReducer' hook to handle multiple inputs in the form. And my component looks like below. As we can see there is a repetetive code. The thing which I would like to fix is 'isValid' for each input. Is it even possible to handle this or this is ok to repeat this code. I am not professional, I am just learning React and you know, everyone tells me about DRY principle.
const initialReducerValue = {
name: '',
lastName: '',
phoneNumber: '',
city: '',
street: '',
postal: '',
nameIsValid: false,
lastNameIsValid: false,
phoneNumberIsValid: false,
cityIsValid: false,
streetIsValid: false,
postalIsValid: false,
formIsValid: false
}
const OrderForm = () => {
const orderReducer = (state, action) => {
if (action.type === 'HANDLE TEXT CHANGE') {
return {
...state,
[action.field]: action.payload,
}
}
}
const [formState, formDispatch] = useReducer(orderReducer, initialReducerValue)
console.log(formState)
const changeTextHandler = (e) => {
formDispatch({
type: 'HANDLE TEXT CHANGE',
field: e.target.name,
payload: e.target.value
})
}
return (
<div className={styles.orderForm}>
<label htmlFor='name'>Name</label>
<input onChange={changeTextHandler} id="name" name='name' type='text' />
<label htmlFor='lastName'>Last Name</label>
<input onChange={changeTextHandler} id="lastName" name='lastName' type='text' />
<label htmlFor='phoneNumber'>Phone Number</label>
<input onChange={changeTextHandler} id="phoneNumber" name='phoneNumber' type='number' />
<label htmlFor='city'>City</label>
<input onChange={changeTextHandler} id="city" name='city' type='text' />
<label htmlFor='street'>Street</label>
<input onChange={changeTextHandler} id="street" name='street' type='text' />
<label htmlFor='postal'>Postal Code</label>
<input onChange={changeTextHandler} id="postal" name='postal' type='text' />
{<SendOrderButton isValid={formState.isValid} /> }
</div>
)
}
I would create an object so you can associate action.field with its corresponding isValid. You could also attach a validation function.
const map = {
name: { isValidName: 'nameIsValid' },
// ..etc
}
and in your reducer -
const mapValue = map[action.field];
return {
...state,
[action.field]: action.payload,
[mapValue.isValidName]: true,
}
Instead of true, you could use a validator function like
[mapValue.isValidName]: mapValue.validator(action.payload)