so am making a little web Aplication and this is my first time trying to use firebase and React Js at the same time so my problem is am trying to make a document in fireStore every time a new User Signs up
// this is my SignUp Function
async function signUp(email, password,) {
await createUserWithEmailAndPassword(auth, email, password);
}
/*and Im calling in it my component and as onSubmit Function and passing it the email and password
and this is where things got me a little tricky because wheni tried to pass my CreateDocument Function as a callBack it throws me an error
and this is my CreateDocument
function const creatProfileDocument = (currentuser) => {
setDoc(doc(db, "users", currentuser.uid), {
email: currentuser.email,
age: false,
name: "",
})
};*/
i Really hope someone can help me here
CodePudding user response:
There are generally two ways to go about this - immediately in your signUp
code or via an auth trigger in Firebase Functions.
In Your Signup Code
You can create a document immediately after your async signUp
function:
async function signUp(email, password) {
// This function returns a credential which gives you the user's uid
// which you could then use to create your document
const credential = await createUserWithEmailAndPassword(auth, email, password);
const uid = credential.user.uid
// Create a new document using the uid as the document id
// or however else you want to use this
const ref = firebase.auth().collection("users").doc(uid)
await ref.set({
email,
uid
})
}
The good side of this is that you immediately create the document so you know it's there when your signUp
function returns. The down side is that you have to loosen some security rules to allow users to create documents on this collection from the client. There are plenty of ways to keep it secure, but just be aware of this.
With Cloud Functions
Your signUp
code creates a new auth record in Firebase, and Firebase has Authentication trigger functions that can fire when a new auth record is created or deleted.
exports.createUserDoc = functions.auth.user().onCreate((user) => {
// Your new auth record will have the uid and email on it because
// you used email as the way to create the auth record
return admin.firestore().collection("users").doc(user.uid).set({
email: user.email,
uid: user.uid
})
});
This is a secure way to handle things and doesn't require you to open up any security rules. But the drawback is that trigger functions are not guaranteed to fire immediately. They usually fire in a few seconds, but I've seen it take 30-60 seconds. So if your client-side code needs the document immediately on account creation, this is not a viable option.