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
You need to do this instead:
setModifiedNonFormData(data => {
return ({
...data,
author: {
...data.author,
phone: val
}
})
})}
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.