简体   繁体   English

Firebase 从帐户创建中获取 UID

[英]Firebase get UID from account create

On Creation of an account I need to make 2 collections 1 for Users 1 for Companies.在创建帐户时,我需要为用户创建 2 collections 1,为公司创建 1。 Within each one, I need to capture the UID.在每一个中,我都需要捕获 UID。 I just cant seem to grab it.我似乎无法抓住它。 I keep getting undefined when console.log it.我在 console.log 时一直未定义。

component成分

    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 authContext

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

I have tried everything in the firebase documentation but I believe since I am using context it may process data a bit differently.我已经尝试了 firebase 文档中的所有内容,但我相信因为我使用的是上下文,所以它处理数据的方式可能会有所不同。

The createUser() function is returning a UserCredential object. You can read the user's UID from it. createUser() function 返回一个UserCredential object。您可以从中读取用户的 UID。 Try refactoring the code as shown below:尝试重构代码,如下所示:

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