Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

246
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!