I am creating the authentication side of a web app using Firebase's Google Sign in and would like to see if the newUser.displayName is unique in the Firestore database. My current code doesn't work as I must create the user before accessing the displayName. If I create the user first and then check the displayName, that would cause problems as I would need to go back and delete the user if the condition is not met. Is there a way to access displayName before the user is created?
Signup.js
const handleGoogleSubmit = async (e) => {
e.preventDefault();
setError('');
try {
const available = await usernameAvailability(newUser.user.displayName.replace(/\s/g, ""))
const newUser = await signInWithGoogle(email, password);
const { isNewUser } = getAdditionalUserInfo(newUser)
if (isNewUser) {
await setDoc(doc(db, "users", newUser.user.uid), {
email: newUser.user.email,
uid: newUser.user.uid,
username: newUser.user.displayName.replace(/\s/g, ""),
usernameLowercase: newUser.user.displayName.toLowerCase(),
});
}
navigate('/account');
} catch (error) {
setError(error.message);
console.log(error.message);
}
}
AuthContext.js
const usernameAvailability = async (username) => {
const q = query(collection(db, "users"), where("usernameLowercase", "==", username.toLowerCase()));
const querySnapshot = await getDocs(q)
console.log(querySnapshot.empty, 'querySnapshot.empty')
if (querySnapshot.empty) {
return true
} else {
throw new Error("Username already exists")
}
}