Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

61
Vistas
Is there a way to do not repeat this loop

I have a question I am making React app. The thing is that in useEffect I loop through six items every time when only one thing changes. How to solve it to change only one variable which was changed in reducer function not looping for 6 items when only one was changed, or is it okay to keep code like this?

 const initialReducerValue = {
        name: {
            val: '', 
            isValid: false, 
        },
        lastName: {
            vaL: '',
            isValid: false
        },
        phoneNumber: {
            val: '',
            isValid: false
        },
        city: {
            val: '',
            isValid: false,
        },
        street: {
            val: '',
            isValid: false
        },
        postal: {
            val: '',
            isValid: false
        },
        
    }
    
    const OrderForm = () => {
    
        const orderReducer = (state, action) => {
            if (action.type === 'HANDLE TEXT CHANGE') {
                
                
                return {
                    ...state,
                    [action.field]: {
                        val: action.payload,
                        isValid: true 
                    }
                    
                }
            }
        }
        
    
    
        const [formState, formDispatch] = useReducer(orderReducer, initialReducerValue)
        const [formIsValid, setFormIsValid] = useState(false)
    
        const changeTextHandler = (e) => {
            formDispatch({
                type: 'HANDLE TEXT CHANGE',
                field: e.target.name,
                payload: e.target.value
            })
        }
        
        useEffect(() => {
            const validationArray = []
            for (const key of Object.keys(formState)) {
                validationArray.push(formState[key].isValid)
             }
    
            const isTrue = validationArray.every(item => item)
            setFormIsValid(isTrue)
        }, [formState])
7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This code

const validationArray = []
for (const key of Object.keys(formState)) {
    validationArray.push(formState[key].isValid)
}
    
const isTrue = validationArray.every(item => item)

is equivalent to

const isTrue = Object.values(formState).every(item => item.isValid);

This still iterates over all items when only one was changed, but with a temporary array less.

For six items, I would not spend time trying to optimize this code further, but that's your choice.

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos