5

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>
  );
};

code sandbox demo

How can I migrate immer state to hooks?

Enivia
  • 192
  • 2
  • 11
  • Not sure exactly what is happening with immer, but if you add a shallow `title` property to `state` and then update it `draft.title = 'new value';` changes are triggered and render occurs. It seems the issue is with your `new Node()` instance. – Davin Tryon Jan 14 '21 at 09:25
  • Your immer code is good as it will work with a simple object. You should check if your node instance `state.root`. – HichamELBSI Jan 14 '21 at 09:26
  • May I know how you solved the problem? I think I've been facing the exact same problem and stuck for a while... – Eric Xin Zhang Feb 04 '23 at 20:40

0 Answers0