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

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

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 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