I want to add a field (Username) to a firebase user's document, when i create it.
My logic :
Error : Unhandled error { Error: 5 NOT_FOUND: No document to update: projects/yeu/databases/(default)/documents/users/DchYhQNMS12VYqzSwtEZ8UXYhcD3
I understand that there is no document (not yet) - so my question is how can i make sure that the document will be ready when it's need to be.
CODE:
ReactJS - SignUp event, (using form & OnClick)
export function SignUp() {
const handleSignupSubmit = (event) => {
event.preventDefault();
const registerForm = document.querySelector(".register");
// firebase
const addUserName = firebase.functions().httpsCallable("addUserName");
// register form
const email = registerForm.email.value;
const password = registerForm.password.value;
const fullName = registerForm.fullName.value;
// firebase sign up
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((userAuth) => {
console.log("registered", userAuth);
addUserName({
userName : fullName
}).then(((doc)=>{
console.log("UserName Added", doc);
}))
.catch((error) => {
registerForm.reset();
registerForm.querySelector(".error").textContent = error.message;
});
})
.catch((error) => {
registerForm.querySelector(".error").textContent = error.message;
});
};
Firebase Backend - Auth trigger
// auth trigger (new user signup)
exports.newUserSignUp = functions.auth.user().onCreate((user) => {
// for background triggers you must return a value/promise
return admin.firestore().collection("users").doc(user.uid).set({
userName: 'Temp',
email: user.email,
});
});
Firebase Backend - HTTP Callable method
// http callable function (adding a username)
exports.addUserName = functions.https.onCall((data, context) => {
if (!context.auth) {
throw new functions.https.HttpsError("unauthenticated");
}
const userRef = admin.firestore().collection("users").doc(context.auth.uid);
return userRef.get().then((doc) => {
return userRef.update({
userName: data.userName
})
})
});
Your client app should wait for the document to become available before invoking the callable function. The easiest way to do that is to set up a realtime listener for the expected document, then call the function only after the listener gives you a callback indicating that the document is present and has data.
The pattern is described in more detail in this blog post . You should be able to copy what it's doing very closely.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.