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

86
Vistas
dynamically changing value of nested object when using setState

I have a piece of state which looks as so:

    const [values, setValues] = useState({
        firstName: '',
        lastName: '',
        dateOfBirth: {
            month: '',
            day: '',
            year: ''
        },
        phoneNumber: '',
        gender: '',
        interests: [],
        language: '',
        medicareNumber: ''
    })

I try to reassign the values of month day and year in the dateOfBirth object onChange, what is the syntax to do this and not overwrite any of the other keys in the object?

                        <input
                            value={values.dateOfBirth.month}
                            onChange={(e) => setValues({
                                ...values,
                                dateOfBirth: { month: e.target.value }
                            })}
                            type='number'
                            placeholder='MM'
                        />

                        <input
                            value={values.dateOfBirth.day}
                            onChange={(e) => setValues({
                                ...values,
                                dateOfBirth: { day: e.target.value }
                            })}
                            type='number'
                            placeholder='DD'
                        />

the code above is setting the value of dateOfBirth to only month or only day. But I need all the keys and values to remain the same and only change the value inside the respected key.

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

0

Try:

<input
    value={values.dateOfBirth.month}
    onChange={(e) => setValues({
        ...values,
        dateOfBirth: {
            ...values.dateOfBirth,
            month: e.target.value
        }
    })}
    type='number'
    placeholder='MM'
/>

Or better, try not to have nested state properties.

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