I need help making a handler that will update the nested object state.
Here is the sample code
const [state, setState] = useState({
firstName: '',
lastName: '',
permanentAddress: {
street: '',
city: ''
},
currentAddress: {
street: '',
city: ''
}
});
const handler = (e) => {
setState({...state, [e.target.name]: e.target.value})
}
Then I import a custom textfield
export const CustomTextField = (props) => {
const { handler, ...rest } = props
return (
<TextField {...rest} onChange={handler} />
)
}
Now I know this will only create a new key named street
with the value instead of updating the one already in the state. I have also thought of just adding a prop that will indicate whether it is nested, something like
<CustomTextField cat='permanentAddress' name='street' handler={handler} />
Then I will change the handler to something like this, passing along cat
in the parameter
const handler = (cat, e) => {
if (cat) {
const category = {...state[cat]}
category[e.target.name] = e.target.value
setState({...state, [cat]: category})
} else {
//non-nested update here
}
}
Is there a better way to do this? Thank you!