I have a nested object as state like below -
const [userInfo, setUserInfo] = useState({
author:"",
user: {
name: 'rahul',
email: '[email protected]',
phone: [{ primary: '8888888810' }, { alternate: '7777777716' }]
}
});
I want to have 5 input fields - author, name, email, primary, and alternate and want to use only one handleChange() method to change the fields.
You can find the code I wrote on the link - https://stackblitz.com/edit/react-ngpx7q
Here, I am not able to figure out how to update the state correctly. Any help would be greatly appreciated.
Since this was an interview question then I'd avoid 3rd-party libraries. You can use a switch
statement to handle the differently nested state, namely the name
and email
in the second level and primary
and alternate
in the third level.
const handleChange = (e) => {
const { name, value } = e.target;
switch (name) {
case "name":
case "email":
setUserInfo((userInfo) => ({
user: {
...userInfo.user,
[name]: value
}
}));
break;
case "primary":
case "alternate":
setUserInfo((userInfo) => ({
user: {
...userInfo.user,
phone: userInfo.user.phone.map((el) =>
el.hasOwnProperty(name)
? {
[name]: value
}
: el
)
}
}));
break;
default:
// ignore
}
};