首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Redux-saga firebase onAuthStateChanged eventChannel

Redux-saga firebase onAuthStateChanged eventChannel
EN

Stack Overflow用户
提问于 2018-08-03 12:31:21
回答 4查看 2.5K关注 0票数 7

如何处理残存传奇中的火源状态观测器?

代码语言:javascript
复制
firebase.auth().onAuthStateChanged((user) => {

});

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

据我所知,eventChannel是正确的做法。但我不知道如何使它与firebase.auth().onAuthStateChanged一起工作。

有人能告诉我如何把firebase.auth().onAuthStateChanged放进eventChannel吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-08-16 02:00:53

您可以使用eventChannel。下面是一个示例代码:

代码语言:javascript
复制
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' } }
  ...
}

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

票数 12
EN

Stack Overflow用户

发布于 2018-08-03 22:33:04

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

代码语言:javascript
复制
function onAuthStateChanged() {
  return new Promise((resolve, reject) => {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        resolve(user);
      } else {
        reject(new Error('Ops!'));
      }
    });
  });
}

然后使用打电话方法同步获取user

代码语言:javascript
复制
const user = yield call(onAuthStateChanged);
票数 5
EN

Stack Overflow用户

发布于 2020-06-19 08:12:06

这可以在Saga中处理,例如Redux的以下内容:

代码语言:javascript
复制
// Redux Saga: Firebase Auth Channel
export function* firebaseAuthChannelSaga() {
  try {
    // Auth Channel (Events Emit On Login And Logout)
    const authChannel = yield call(reduxSagaFirebase.auth.channel);

    while (true) {
      const { user } = yield take(authChannel);

      // Check If User Exists
      if (user) {
        // Redux: Login Success
        yield put(loginSuccess(user));
      }
      else {
        // Redux: Logout Success
        yield put(logoutSuccess());
      }
    }
  }
  catch (error) {
    console.log(error);
  }
};
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51672715

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档