firebase 在创建用户时添加用户信息(react.js)

esc*_*ion 2 javascript firebase reactjs firebase-authentication

在问这个问题之前我进行了研究,但找不到答案。

我用react js制作了一个表单。当我单击该按钮时,它会使用 createUserWithEmailAndPassword() 方法创建一个用户。创建用户没有问题。我想添加额外的信息,例如;用户名:“Usernameeeee”到我的数据库。数据库将如下所示:

users {
     userUid1: {name: "Name User 1"}
     userUid2: {name: "Name User 2"}
     ....
       }
Run Code Online (Sandbox Code Playgroud)

当我使用 createUserWithEmailAndPassword() 时,它会创建一个用户并登录。但正如您在上面看到的,我需要当前用户的 ID。我知道如何正常获取它, firebase.auth().currenUser... 但是在创建用户时我无法捕获用户的 id。它返回空;

export function signUpUser({email, password}) {
return function (dispatch){
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(
    () => dispatch({type: USER_SIGNUP_SUCCESS})
)
.then(console.log(firebase.auth().currentUser))
.catch(error => {
    dispatch({type: USER_SIGNUP_FAIL, payload: error.message});
});
}
Run Code Online (Sandbox Code Playgroud)

}

当我控制台当前用户时,创建用户已完成但尚未登录。那么如何在创建用户时添加信息呢?(不是在以其他方式登录后)

esc*_*ion 6

一天后我找到了答案。我希望这对其他人有帮助。如您所知,主要问题是在创建用户之后、用户登录之前获取用户 ID...

所以解决办法是:

export function signUpUser({email, password, username}) {
    const db = firebase.database();
    return function (dispatch){
    firebase.auth().createUserWithEmailAndPassword(email, password)
      // here we get user id if creating is successful.
    .then(function(user){
        dispatch({type: USER_SIGNUP_SUCCESS}); // I dispatched some message.
        db.ref(`users/${user.uid}`).set({name: username}); // I added user
        console.log('uid:',user.uid)

})
Run Code Online (Sandbox Code Playgroud)