【问题标题】:how to get firebase use in nextJS getserversideprops如何在 nextJS getserversideprops 中使用 firebase
【发布时间】:2021-08-10 00:18:53
【问题描述】:

如果有签名用户,我想使用 getServerSideProps 在 Firestore 中获取“示例”文档。 下面的代码不起作用。结果是“无法阅读” 我该怎么办?还是有其他方法?

export const getServerSideProps = () => {
  let currentUser = []

  authService.onAuthStateChanged(async user => {
      if(user) {
        const docRef = dbService.collection('whole_users').doc('sample').get()
        await docRef.then((doc) => {
          if(doc.exists) {
            currentUser.push(doc.data())
          }
        })
      } else {
        console.log("can't read")
      }
    })

  return {
    props: {currentUser}
  }
}

【问题讨论】:

  • 这一行的用户是从哪里传来的? authService.onAuthStateChanged(async user => {您是否尝试注销用户值?
  • 它只是“onAuthStateChanged”参数。如果“onAuthStateChanged”中有数据,我尝试将数据放入 currentUser。

标签: javascript firebase-authentication next.js


【解决方案1】:

第一个: 你打电话给get() 没有await。将您的代码更改为:

export const getServerSideProps = () => {
  let currentUser = []

  authService.onAuthStateChanged(async user => {
      if(user) {
        const docRef = dbService.collection('whole_users').doc('sample')
        await docRef.get().then((doc) => {
          if(doc.exists) {
            currentUser.push(doc.data())
          }
        })
      } else {
        console.log("can't read")
      }
    })

  return {
    props: {currentUser}
  }
}

第二个:onAuthStateChanged 仅用于客户端。要访问服务器端的身份验证状态,您需要将身份验证状态放入提供程序。 Here 是一个例子。

【讨论】:

  • 谢谢,但它不起作用。我想知道为什么我不能在 getServerSideProps 中访问“onAuthStateChanged”,而我可以在组件中访问。
  • 啊抱歉,我刚刚看到错误的get() 电话。我已经更新了答案。基本上,最好的方法是将身份验证状态放入提供程序,以便您可以按预期访问它。有一篇文章的链接详细解释了它。
猜你喜欢
  • 2021-09-25
  • 2021-12-31
  • 2021-01-13
  • 2021-12-02
  • 2022-10-23
  • 2020-07-25
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
相关资源
最近更新 更多