簡體   English   中英

如何為預期創建的文檔增加價值? (Firebase + 反應)

[英]How do I add value to a document that is expected to be created? (Firebase + React)

我想在創建它時向 firebase 用戶的文檔添加一個字段(用戶名)。

我的邏輯:

  1. 用電子郵件,通行證和用戶名字段填寫表格 - 有效。
  2. 獲取電子郵件並通過並注冊 firebase (createUserWithEmailAndPassword) - WORKS。
  3. 在文檔創建之后(希望如此) - 觸發一個 HTTP Firebase 可調用,它將更新表單中的 userName 字段 - FAILED

錯誤:未處理的錯誤 { 錯誤:5 NOT_FOUND:沒有要更新的文檔:projects/yeu/databases/(默認)/documents/users/DchYhQNMS12VYqzSwtEZ8UXYhcD3

我知道沒有文件(還沒有) - 所以我的問題是我如何確保文件在需要時准備好。

代碼:

ReactJS - 注冊事件,(使用表單和 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 后端 - 身份驗證觸發器

// 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 后端 - HTTP 可調用方法

// 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
    })
  })
});

在調用可調用函數之前,您的客戶端應用程序應等待文檔可用。 最簡單的方法是為預期的文檔設置一個實時偵聽器,然后僅在偵聽器給您一個回調指示該文檔存在並且有數據后才調用該函數。

這篇博文中更詳細地描述了該模式。 您應該能夠非常密切地復制它正在做的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM