【问题标题】:How can I use a promise to see if firebase auth is loaded?如何使用承诺来查看是否已加载 firebase 身份验证?
【发布时间】:2020-06-13 00:10:11
【问题描述】:

注意:我使用的是 react js,我所有的代码都在一个 react 组件类中。

我想检查某人是否是管理员,所以我做了这个功能:

makeDatabaseCall = () => {

    let userDB = this.props.firestore.collection('user');
    let queryUserDB = userDB.where('userIdentifier', '==', this.props.auth.uid).limit(1).get()

        .then(snapshot => {
            console.log(snapshot.docs[0].data().clearance)

            return (
            this.setState({
            clearance: snapshot.docs[0].data().clearance 
            })
            )
        })
        .catch(err => {
            console.log('Error getting documents', err);
        });
}

但是我需要使用this.props.auth.uid,所以需要等到auth加载完毕。

我不想把它放在我的 render() 中的 if 语句中,因为这会使我的代码效率低下(它会一直检查)。

如何使用promise的概念对firebase进行异步调用,查看是否加载了auth,然后然后运行上面的函数?

这也是我的验证码:

const mapStateToProps = (state) => {
    return {
        auth: state.firebase.auth
    }
}

export default compose(
    connect(mapStateToProps),
    firestoreConnect([
        { collection: 'events',
        collection: "user"
     }
    ])
)(Dashboard)```

【问题讨论】:

  • 您确实需要提供更多信息,例如,您在哪里加载auth?显示上下文中使用的代码。另外,FWIW,我不完全理解为什么你认为如果你把代码放在 if 后面,它会一直检查,根据 if 语句的定义,它只会检查 if条件为真。
  • 好吧,如果它在 render() 中,则需要继续检查。我将添加其他代码。谢谢!

标签: reactjs firebase promise firebase-authentication


【解决方案1】:

这实际上不是您想要使用的策略。您应该使用auth state listener 中所述的documentation 来在用户登录或注销时接收回调。您可以使用此回调来准确确定用户何时登录,并获取用于查询的 UID。您可能不想尝试将其转换为承诺,因为无法保证用户何时在您的应用程序中实际执行此操作。当用户登录时,您的侦听器应根据需要启动任何查询(或使用您使用的任何框架,例如 RxJS)发送其他信号。

【讨论】:

  • 如何在类中调用它?
  • 不确定你在问什么。您在回调中编写代码以响应链接文档中的状态变化。
  • 好吧,我一直收到这个错误:TypeError: this.props.auth.onAuthStateChanged is not a function
猜你喜欢
  • 2016-09-26
  • 2017-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-08
  • 2018-12-28
  • 1970-01-01
  • 2020-09-05
相关资源
最近更新 更多