I have a React component that has some form fields in it:
<TextField
label="Description"
id="description"
value={company.companyDescription}
onChange={updateFormField("companyDescription")}
></TextField>
and a function that updates my company state whenever the values change:
const updateFormField = (property: string) => (event: ChangeEvent<HTMLInputElement>) => {
setCompany(prev => ({ ...prev, [property]: event.target.value }))
}
This means that whenever a form field changes I'd like to create a new copy (hence the spread operator) of the old object.
My problem is that company has nested properties in it, like company.location.address
:
{
name: "some company",
location: {
address: "some street"
}
// ...
}
Is there a way to refactor the above function to update the nested properties? For example something like:
const updateFormField = (property: string[]) => (event: ChangeEvent<HTMLInputElement>) => {
setCompany(prev => ({ ...prev, [...property]: event.target.value }))
}
I don't think there's a particularly neat solution to this, however it should be possible to loop through selecting/adding the new path:
const updateFormField = (property: string[]) => (event: ChangeEvent<HTMLInputElement>) => {
setCompany(prev => {
// Take a copy of the state
const newObj = { ...prev }
// Set up a refernce to that object
let selected = newObj
// Loop through each property string in the array
for (let i = 0; i < property.length; i++) {
// If we're at the end of the properties, set the value
if (i === property.length - 1) {
selected[property[i]] = event.target.value
} else {
// If the property doesn't exist, or is a value we can't add a new property to, set it to a new object
if (typeof selected[property[i]] !== 'object') {
selected[property[i]] = {}
}
// Update our refernce to the currently selected property and repeat
selected = selected[property[i]]
}
}
// Return the object with each nested property added
return newObj
)}
}
Plain JS working example of the same method:
const test = (prev, property, value) => { const newObj = { ...prev } let selected = newObj for (let i = 0; i < property.length; i++) { if (i === property.length - 1) { selected[property[i]] = value } else { if (typeof selected[property[i]] !== 'object') { selected[property[i]] = {} } selected = selected[property[i]] } } return newObj } console.log(test( {"a": "1"}, ["b", "c", "d"], 100 )) console.log(test( {"a": "1"}, ["a", "b"], 100 )) console.log(test( {"a": {"b": {"c": 1}}}, ["a", "b", "c"], 100 ))
Object.assign() and dynamically finding the inner reference should do it. I'm assuming the input type of string[] above indicates the nested path is an array like ['company', 'location', 'address']:
const updateFormField = (property: string[]) => (event: ChangeEvent<HTMLInputElement>) => {
setCompany(prev => {
const copy = Object.assign({}, prev);
let ref = copy;
for (let i = 0; i < property.length - 1; i++) {
ref = ref[property[i]];
}
ref[property[property.length - 1]] = event.target.value
return copy;
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.