Mobx-state-tree: Introduce lifecycle hooks for models

Created on 7 Apr 2017  路  5Comments  路  Source: mobxjs/mobx-state-tree

suggestions:

  • beforeDispose
  • afterCreate
  • beforeApplySnapshot
  • afterApplySnapshot
  • afterCreateSnapshot
  • beforeChange (like intercept)

..But only if there are good use cased :-D

brainstorminwild idea

Most helpful comment

Naming convention before/after resonates better with me.

All 5 comments

+1

afterCreateInstance to setup reactions! :D

Proposal:

  • preprocessSnapshot(snapshot) => snapshot (called before applying a snapshot, both during create and later on)
  • postprocessSnapshot(snapshot) => snapshot (called when creating a snapshot)
  • didCreate() called after instantation, but not during reconcilation
  • didAttach() called when node gets attached to a tree (not called if attached before creation)
  • willDetach() called before detaching from a tree
  • willDestroy() called before a node is killed

Naming convention before/after resonates better with me.

@mweststrate Maybe add a preprocess and postprocess for patches too?

Merged by #98 and released as 0.3.3.

Following lifecycle hooks are now available:

  • afterCreate
  • beforeDestroy
  • afterAttach
  • beforeDetach

More lifecycle hooks should be demand / use case driven. E.g. processing snapshots.

Also introduced the convenience method addDisposer which is useful in afterCreate, avoid the need to setup a beforeDestroy just to fire disposers.

E.g.:

const Todo = types.model({
   afterCreate() {
       addDisposer(this, reaction(() => getSnapshot(this), s => submitSnapshotToServer(s)))
   }
})
Was this page helpful?
0 / 5 - 0 ratings

Related issues

mshibl picture mshibl  路  3Comments

erkieh picture erkieh  路  4Comments

lidermanrony picture lidermanrony  路  3Comments

lishine picture lishine  路  4Comments

donatoaz picture donatoaz  路  3Comments