React hooks: How do I update state on a nested object with useState()?
This is your mistake
setStyle({
...style,
font: { align: event.target.value } // This code replace the font object
});
To preserve the all font
object values, you can do like this
const onChange = (event) => {
const s = {...style};
s.font.align = event.target.value;
setStyle(s);
}
Or
const onChange = (event) => {
setStyle({
...style,
font: {
...style.font, // Spread the font object to preserve all values
align: event.target.value
}
});
}
You need to use spread syntax to copy the font object properties too. Also while trying to update current state based on previous, use the callback pattern
<RadioButtonGroup
onChange={(event) => {
setStyle(prevStyle => ({
...prevStyle,
font: { ...prevStyle.font, align: event.target.value }
}));
console.log(style);
}}
/>
If you have multiple values in a nested object, try this method below:
setPost({
...post,
postDetails: {
...post.postDetails,
[event.target.name]: event.target.value,
},
});