Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

99
Vistas
how to shorten useReducer

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>

        
    )
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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)
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda