javascriptreactjsmobxmobx-state-treemobx-react-lite

Observer does not work for recursive items


I'm really stuck with the problem. I have a nested menu. After click on the first menu level second level items shows up. After click on one of the children nothing happens. Looks like the observer don't work for deep levels items. I don't know if the "late" type could be a problem. Everything is described in the code: https://codesandbox.io/s/mobx-state-tree-recursive-deep-menu-p7eqj

Thanks in advance


Solution

  • The problem is that when you are using your recursive TreeItem component it is not actually observer. You wrapping it in observer only when exporting, but TreeItem inside TreeItem is regular component, not observer so it doesn't react to anything.

    Basically you just need to move observer decorator:

    // Use `observer` right here straight away
    const TreeItem = observer((props) => {
      const handleClick = () => {
        props.item.active ? props.item.deactivate() : props.item.activate();
      };
    
      const ItemChildren = ({ children }) => {
        return (
          <ul>
            {children.map((child) => (
              <TreeItem key={child.id} item={child} />
            ))}
          </ul>
        );
      };
    
      return (
        <React.Fragment>
          <li onClick={handleClick}>{props.item.id}</li>
          {props.item.active && (
            <ItemChildren children={values(props.item.children)} />
          )}
        </React.Fragment>
      );
    });
    
    // Remove it from here
    export default TreeItem;
    

    Codesandbox