Home > Enterprise >  Firebase get UID from account create
Firebase get UID from account create

Time:01-30

On Creation of an account I need to make 2 collections 1 for Users 1 for Companies. Within each one, I need to capture the UID. I just cant seem to grab it. I keep getting undefined when console.log it.

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

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.

CodePudding user response:

The createUser() function is returning a UserCredential object. You can read the user's UID from it. 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
  })
}
  • Related