Search code examples
javascriptmobxmobx-state-tree

What's a good practice to call an action from another action of the same model in mobx-state-tree?


I am trying to wrap multiple functions inside one.

I have a model like this:

const CookModel = types.actions(self =>({
  talkToSousChefs:() => {
    // talk to sous-chefs
  },
  talkToWaiters: () => {
    // business logic
  },
  talkToVendors: () => {
    // business logic
  },
  runTalkRoutine: () => {
    // current code

    const root = getRoot<typeof CookModel>(self)

    root.talkToSousChefs()
    root.talkToVendors()
    root.talkToWaiters()

    // what's the best practice?
  }
}))

What's the best way to wrap those actions in runTalkRoutine?


Solution

  • That would do it but I would use self directly

      runTalkRoutine: () => {
        self.talkToSousChefs()
        self.talkToVendors()
        self.talkToWaiters()
      }
    

    If any of your actions are async you can use yield

    If you want autocomplete you can move the runTalkRoutine to another actions block

    const CookModel = types.actions(self =>({
      talkToSousChefs:() => {
        // talk to sous-chefs
      },
      talkToWaiters: () => {
        // business logic
      },
      talkToVendors: () => {
        // business logic
      }
    })).actions(self => ({
      runTalkRoutine: () => {
        // here you will have autocomplete on self
        self.talkToSousChefs()
        self.talkToVendors()
        self.talkToWaiters()
      }
    }))