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

251
Vistas
error in updating usehook object using spread operator

How to target a key when I have multiple alike keys in an object. If I try to target my desired key, it shows a syntax error.

const [modifiedNonFormData, setModifiedNonFormData] = useState({
"author": {
    "lastName": "",
    "location": {
        "latitude": 49.3542671,
        "longitude": 8.133071
    },
    "shippingAddress": {
        "postalCode": "",
        "name": "",
        "address": "",
        "location": {
            "longitude": "",
            "latitude": ""
        },
        "email": "",
        "phone": "+14356234653"
    },
    "phone": "+14356234653",
    "firstName": e.target.value
},})


const phoneHandler = (e) => {
let val = e.target.value
setModifiedNonFormData(modifiedNonFormData => {
    return (
        ...modifiedNonFormData,
        ...modifiedNonFormData.author.phone:val
    )
})}

I am trying to update/modify onChange input value

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

0

You need to do this instead:

setModifiedNonFormData(data => {
    return ({
        ...data,
        author: {
           ...data.author,
           phone: val
        }
    })
})}

Explanation

You need to return a new object to a state setter in react. A common way to do this is through object destructuring. Let's say you have data and you want to clone it. You can do:

const newData = { ...data }

This would copy all of the values from data to a new object. This is also the reason why modifying data works - you are copying the values but also setting a new value for a property:

const newData = { ...data, newProperty: newValue }

However, this syntax is limited to replacing the value of a property. Therefore, if you want to modify the value of a property in an nested object, you have to also use the same syntax inside.

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