如何在 nextJS getserversideprops 中使用 firebase

时间:2021-05-20 17:47:25

标签: firebase-authentication next.js getserversideprops

如果有签名用户,我想使用 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}
  }
}

1 个答案:

答案 0 :(得分: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 是一个示例。