I store a Node entity in state. When I click the button, I want to change the property 'title', and trigger component update to display the new title value. Nothing happens in the function component, it's only updated in class component.
class component:
class ClassTest extends Component {
state = {
root: new Node()
};
render() {
const { root } = this.state;
return (
<div>
<div>class component: {root.title}</div>
<button
onClick={() =>
this.setState(
produce((draft) => {
draft.root.title = "title changed";
})
)
}
>
change
</button>
</div>
);
}
}
function component:
const FunctionTest = () => {
const [state, setState] = useState({ root: new Node() });
const { root } = state;
return (
<div>
<div>function component: {root.title}</div>
<button
onClick={() =>
setState(
produce((draft) => {
draft.root.title = "title changed";
})
)
}
>
change
</button>
</div>
);
};
How can I migrate immer state to hooks?