skip to Main Content

I am usinf firebase authentication and firebase database to create a user account for my app. I have authentication working, it creates the account, but when it moves on to save user details to the database, its saying that the key is empty, even though i was able to console log the key and the value shows.

import React, { useState } from "react";
import { useFormik } from "formik";
import { emailRegex } from "../components/Utilities/validations";
import { createUserWithEmailAndPassword } from "firebase/auth";
import { auth } from "../components/firebase";
import { ref, set } from "firebase/database";
import { database } from "../components/firebase";

export default function () {
  const [userID, setUserID] = useState("");
  const validate = (values) => {
    const errors = {};
    if (!values.repassword !== values.password) {
      errors.repassword = "passwords do not match";
    }

    if (!emailRegex.test(values.email)) {
      errors.email = "invalid email";
    }
    if (values.phone.length < 10) {
      errors.phone = "enter valid phone number including area code";
    }
  };

  const formik = useFormik({
    initialValues: {
      email: "",
      password: "",
      repassword: "",
      first_name: "",
      last_name: "",
      phone: "",
      street_address: "",
      street_address_2: "",
      city: "",
      state: "",
      postal_code: "",
      country: "",
    },
    validate,
    onSubmit: (values) => {
      createUserWithEmailAndPassword(auth, values.email, values.password)
        .then((userCredential) => {
          const user = userCredential.user;
          console.log(auth.currentUser.uid);
          setUserID(auth.currentUser.uid);
          console.log("This is my key " + auth.currentUser.uid);
        })
        .then(() =>
          set(ref(database, "users/" + userID), {
            email: email,
            first_name: first_name,
            last_name: last_name,
            phone: phone,
            street_address: street_address,
            street_address_2: street_address_2,
            city: city,
            state: state,
            postal_code: postal_code,
            country: country,
            userID: auth.currentUser.uid,
          })
        )

        .catch((error) => {
          const errorCode = error.code;
          const errorMessage = error.message;
          console.log(errorMessage);
        });
    },
  });

2

Answers


  1. Chosen as BEST ANSWER

    I used an async function instead, this allowed me to have access to the auth.currentUser object in the then chain

    const createUserAccount = async (values) => {
          const response = await createUserWithEmailAndPassword(
            auth,
            email,
            password
          )
            .then((user) => {
              if (auth.currentUser.uid !== null) {
                set(ref(database, "users/" + auth.currentUser.uid), {
                  first_name: fname,
                  last_name: lname,
                  phone: phone,
                  email: email,
                  address: address,
                });
    
                console.log("data written to db");
              } else {
                console.log("empty uid");
              }
            })
            .catch((error) => {
              const errorCode = error.code;
              const errorMessage = error.message;
              setErrors({ email: errorMessage });
    
              console.log(errorMessage);
            });


  2. React useState hook is asynchronous. So, it won’t have the UID that you are setting at the time when you’re using it. So it’s better to use it directly from auth.currentUser.uid instead of setting it into a hook and then using it.

    ...
    set(ref(database, "users/" + auth.currentUser.uid), {
    ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search