mobxjs / mobx-react

React bindings for MobX
https://mobx.js.org/react-integration.html
MIT License
4.85k stars 350 forks source link

lifecycle hooks for mobx #874

Closed devdoomari3 closed 4 years ago

devdoomari3 commented 4 years ago

I'm looking for a lifecycle functions for mobx, similar to mobx-state-tree (https://mobx-state-tree.js.org/overview/hooks)

is there some way to define custom init/dispose functions that are automatically called by mobx-react ?

my guess is that because mobx-state-tree is rendered using mobx-react, mobx should have a way to define custom init/dispose functions...

Is there something I missed?

thank you!

danielkcz commented 4 years ago

Can you elaborate on some code example what you are trying to achieve?

devdoomari3 commented 4 years ago

like:

class SomeObservable {
  constructor() { }
  async init() { // called automatically by mobx-react (reference-counted)
    const data = await fetchData();
    this.propA = data.propA;
    // etc
    this.socketConnection = await connectSocket(..)
  }
  async dispose() { // same here
    await this.socketConnection.close
  }
}

looking at mobx-utils, fromResource seems to be the answer... but I'm not so sure

urugator commented 4 years ago

Not exactly sure what are you asking for, but you can use mobx.onBecome(Un)Observed to get notified when a certain (single) observable (eg observable that exposes an instance of SomeObservable) becomes or stops being consumed by at least one reaction. It doesn't count the references, but number of observers.

devdoomari3 commented 4 years ago

@urugator yes that's what I was looking for 👍

closing!