简体   繁体   中英

React Mobx Firebase.onAuthStateChanged listener

I have always put my auth.onAuthStateChange().then(user => ... inside the componentDidMount() of a top level React component.

Then I would remove the listener inside of componentWillUnmount()

My question is how would i mobx-ify this? My idea is something like this:

class Store {
  @observable user = null
  @action killFirebaseListener = this.removeListener()
  constructor() {
    this.removeListener = firebase.auth().onAuthStateChange(user => {
      if (user) this.user = user
    })
  }
}

I would then call the killFirebaseListener action from the componentWillUnmount of a top level container-component... and just use the user observable where necessary. It is my understanding that when my user observable updates upon a successful login or logout, all my listeners will update and trigger a re-render accordingly... am i wrong about this?

Does anyone have experience with this sort of "user listener" with mobx? Does anyone have any pointers or maybe resources that they can pass along.

OK. Looks like my idea works just fine. I added

class Store {
  @observable user = null
  constructor() {
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        this.user = user
      }
    })
  }
}

and the listener works just fine / updates without issue.

For anyone struggling with react-mobx-firebase integration, i wrote an open source toolkit that that does everything for you. firestore integration, auth, optional inline admin UI, simple rendering and more. hope someone will find this useful. it's called orkan , check it out.

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