简体   繁体   中英

Reusable actions in mobx/mobx-state-tree

I have multiple mobx stores and find myself having actions in each of them that are pretty much identical. I'm therefor hoping to be able to generalise and reuse them between stores. Below I have tried to break out the create action hoping to be able to import it to multiple stores but it doesn't work as self is not available.

I want to go from this:

export const CategoriesStore = types
  .model("CategoriesStore", {
  })
  .views(self => ({
  }))
  .actions(self => {
    const collection = "categories"

    const create = flow(function* create(newItem) {
      const newItemRef = firestore.collection(collection).doc()
      const id = newItemRef.id
      self[collection].set(id, newItem)
      yield newItemRef.set(newItem)
      return id
    })
 return {
   create
 }
})

To something like this, where the create action could be reused in other stores:

const create = flow(function* create(newItem, collection) {
    const newItemRef = firestore.collection(collection).doc()
    const id = newItemRef.id

    this[collection].set(id, newItem)
    yield newItemRef.set(newItem)

    return id
})

export const CategoriesStore = types
  .model("CategoriesStore", {
  })
  .views(self => ({
  }))
  .actions(self => {
    const collection = "categories"

    const _create = create.bind(self)

    return {
      _create
    }
})

Any ideas for how to achieve this?

While I've never done anything like that, but I was thinking to and had an impression that it should work. But if it doesn't, you can do something like:

const create = (self) => flow(function* create(newItem, collection) {
  const newItemRef = firestore.collection(collection).doc()
  const id = newItemRef.id

  self[collection].set(id, newItem)
  yield newItemRef.set(newItem)

  return id
})

export const CategoriesStore = types
.model("CategoriesStore", {
})
.views(self => ({
}))
.actions(self => {
  const collection = "categories"

  return {
    create: create(self)
  }
})

This should definitely work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM