Redux传奇Firebase onAuthStateChanged eventChannel

ren*_*dom 3 firebase firebase-authentication redux-saga

如何在Redux传奇中处理Firebase身份状态观察器?

firebase.auth().onAuthStateChanged((user) => {

});
Run Code Online (Sandbox Code Playgroud)

我想APP_START在我的应用启动时运行saga,它将运行firebase.auth().onAuthStateChanged观察程序,并根据回调运行其他sagas。

据我了解,eventChannel是正确的方法。但是我不知道如何使它与firebase.auth().onAuthStateChanged

有人可以显示如何放入firebase.auth().onAuthStateChangedeventChannel吗?

vah*_*san 7

您可以使用eventChannel。这是示例代码:

function getAuthChannel() {
  if (!this.authChannel) {
    this.authChannel = eventChannel(emit => {
      const unsubscribe = firebase.auth().onAuthStateChanged(user => emit({ user }));
      return unsubscribe;
    });
  }
  return this.authChannel;
}

function* watchForFirebaseAuth() {
  ...
  // This is where you wait for a callback from firebase
  const channel = yield call(getAuthChannel);
  const result = yield take(channel);
  // result is what you pass to the emit function. In this case, it's an object like { user: { name: 'xyz' } }
  ...
}
Run Code Online (Sandbox Code Playgroud)

完成后,您可以使用关闭频道this.authChannel.close()


And*_*aci 5

创建您自己的函数onAuthStateChanged(),该函数将返回一个Promise

function onAuthStateChanged() {
  return new Promise((resolve, reject) => {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        resolve(user);
      } else {
        reject(new Error('Ops!'));
      }
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

然后使用call方法user同步获取

const user = yield call(onAuthStateChanged);
Run Code Online (Sandbox Code Playgroud)