How to Change Parent State from Child - Mobx State Tree?
Asked Answered
L

1

5

I am trying to make a Nav in reactjs with Mobx State Tree.

Right now I have skinny vertical Nav bar with a list of icons. Now what I want to do is add sub menu items to certain ones. When these ones are clicked the Nav goes from skinny to wide(ie expands) and the sub menu items are shown. Once a user clicks on one of them the Nav goes back to skinny version.

What I think I need is a way that when an icon is clicked in my parent store a flag gets set to say "expand" but I don't know how to set that when a child gets clicked.

import { types } from "mobx-state-tree";
import NavItem from "./NavItem.js";
const NavStore = types
  .model("NavStore", {
    expanded: false,
    nav_items: types.array(NavItem)
  })
  .actions(self => ({}))
  .views(self => ({}))
  .create({

  });

export default NavStore;


import { types } from "mobx-state-tree";

const NavItem = types
  .model("NavItem", {
     expands: false,
     title: types.string
  })
  .actions(self => ({
    itemClicked() {

    }
  }))
  .views(self => ({}));

export default NavItem
Litalitany answered 4/6, 2018 at 22:32 Comment(0)
T
7

You need to import getParent and (optionaly) hasParent functions:

import { types, getParent, hasParent } from ‘mobx-state-tree’

Then in your action call parent’s action:

if (hasParent(self)) {
  getParent(self).someAction(someParams);
}
Tunnage answered 6/6, 2018 at 17:23 Comment(4)
I seen people do getParent(self, #). What is the difference vs something like getParent(self, 1)Litalitany
Second parameter - depth (default is 1). So you can write getParent(self, 2) to get parent of the parent. I think there is no reason to write # for the depth, because it should be a number.Tunnage
I've check source code (github.com/mobxjs/mobx-state-tree/blob/master/packages/…) and seems getParent should raise an exception if second argument is not a number.Tunnage
yeah but the default value is 1Xenophanes

© 2022 - 2024 — McMap. All rights reserved.