Using Firebase v9, how can I add the user to the user collection upon logging in with gmail? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Using Firebase v9, how can I add the user to the user collection upon logging in with gmail? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

How can I add a user to the users collection logging in with Gmail?
I tried the addUser but it does not work. I’m quite new to Firebase v9

//firebase
    import { signInWithPopup, GoogleAuthProvider } from "firebase/auth";
    import { auth, signInWithGoogle, db } from "../../Firebase/utils";
    import { doc, setDoc, collection } from "firebase/firestore";

const Login = (props) => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const addUser = async () => {
    const userRef = doc(db, "users", auth.currentUser);
    setDoc(userRef);
  };

  useEffect(() => {
    addUser();
  }, []);

  const googleHandler = async () => {
    signInWithGoogle.setCustomParameters({ prompt: "select_account" });
    signInWithPopup(auth, signInWithGoogle)
      .then((result) => {
        // This gives you a Google Access Token. You can use it to access the Google API.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const token = credential.accessToken;
        // The signed-in user info.
        const user = result.user;
        // redux action? --> dispatch({ type: SET_USER, user });
        addUser();
        console.log(auth.currentUser, "login page");
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.email;
        // The AuthCredential type that was used.
        const credential = GoogleAuthProvider.credentialFromError(error);
        // ...
      });
  };

  return (
    <>
        <form>
           <Button onClick={googleHandler}>Login with Gmail</Button>
        </form>
    </>
  );
};

export default Login;

These are my package.json just to be sure:

enter image description here

This is what the console.log(auth.currentUser) shows: enter image description here

UPDATE:

const addUser = async (userId) => {
    const userRef = doc(db, "users", userId);
    return await setDoc(userRef, { ...data });
  };

  useEffect(() => {
    addUser();
  }, []);

  const googleHandler = async () => {
    signInWithGoogle.setCustomParameters({ prompt: "select_account" });
    signInWithPopup(auth, signInWithGoogle)
      .then(async (result) => {
        // This gives you a Google Access Token. You can use it to access the Google API.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const token = credential.accessToken;
        // The signed-in user info.
        const user = result.user;
        // redux action? --> dispatch({ type: SET_USER, user });
        // addUser();

        const { isNewUser } = getAdditionalUserInfo(result);
        if (isNewUser) {
          await addUser(user.uid);
        } else {
          console.log("User already exists");
        }
      })

      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.email;
        // The AuthCredential type that was used.
        const credential = GoogleAuthProvider.credentialFromError(error);
        // ...
      });
  };

Answer

The doc() function takes Firestore instance as first argument and the rest are path segments (strings) so you cannot pass currentUser object there. Also there might be a chance that auth.currentUser. You can use isNewUser property to check if the user has just signed up or is logging in again and then add the document. Try refactoring the code as shown below:

signInWithPopup(auth, signInWithGoogle)
  .then(async (result) => {
    const user = result.user;
    
    const { isNewUser } = getAdditionalUserInfo(result)
    if (isNewUser) {
      await addUser(user.uid); 
    } else {
      console.log("User already exists")
    }
})

const addUser = async (userId) => {
  const userRef = doc(db, "users", userId);
  return await setDoc(userRef, {...data});
};
We are here to answer your question about Using Firebase v9, how can I add the user to the user collection upon logging in with gmail? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji