簡體   English   中英

Firebase 從帳戶創建中獲取 UID

[英]Firebase get UID from account create

在創建帳戶時,我需要為用戶創建 2 collections 1,為公司創建 1。 在每一個中,我都需要捕獲 UID。 我似乎無法抓住它。 我在 console.log 時一直未定義。

成分

    const handleSubmit = async (e) => {
        e.preventDefault()
        setError('')
        try {
            await createUser(email, password).then(() => {
                if (false) throw Error('Error')
                //NEED Get UserID
                addDoc(collection(db, 'Companies'), {
                    name: company,
                    //owner: userID,
                    users: [],
                    assets: []
                }).then((docRef) => {
                    let companyID = docRef.id
                    addDoc(collection(db, 'Users'), {
                        name: name,
                        email: email,
                        company: [company],
                        companyID: [companyID]
                        //UserID: UserID
                    })
                })
            })

authContext

export const AuthContextProvider = ({ children }) => {
    const [user, setUser] = useState({})
    const createUser = (email, password) => {
        return createUserWithEmailAndPassword(auth, email, password)
    }

我已經嘗試了 firebase 文檔中的所有內容,但我相信因為我使用的是上下文,所以它處理數據的方式可能會有所不同。

createUser() function 返回一個UserCredential object。您可以從中讀取用戶的 UID。 嘗試重構代碼,如下所示:

const handleSubmit = async (e) => {
  e.preventDefault()
  setError('')

  const { user } = await createUser(email, password)

  const docRef = await addDoc(collection(db, 'Companies'), {
    name: company,
    owner: user.uid,
    users: [],
    assets: []
  })

  await addDoc(collection(db, 'Users'), {
    name: name,
    email: email,
    company: [company],
    companyID: [docRef.id]
    UserID: user.uid
  })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM