Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda