注册时ReactNative和firebase,实时数据库

时间:2018-03-22 20:59:53

标签: javascript reactjs firebase react-native firebase-realtime-database

我使用此字段(电子邮件,密码,名称和电话)构建一个react native signUp表单,我需要在用户创建其帐户时将其添加到firebase数据库。

我创建了这样的signUp函数:



onSignUpPress() {
    const navigation = this.props.navigation;
      this.setState({ error: '', loading: true });
      const { email, password } = this.state;
      firebase.auth().createUserWithEmailAndPassword(email, password)
          .then(() => {
        this.setState({ error: '', loading: false }); 
        navigation.navigate("Profile");
      })
                  .catch(() => {
                      this.setState({ error: 'Authentication failed.', loading: false });
                      console.log("Error creating user:");
                  });
  }




及其工作

我需要知道如何将字段添加到数据库

我试试这个:



writeUserData(uid, name, email, phone) {
    let userId = firebaseApp.auth().currentUser.uid;
    var newUser = {
      name: name,
      email: email,
      phone: phone
    }

  var newUserKey =  firebase.database().ref().child('users').push().key;
  var updates = {};
updates['/users/' + newUserKey] = newUser;
updates['/user-users/' + uid + '/' + newPostKey] = postData;

return firebase.database().ref().update(updates);
  }






  onSignUpPress() {
    ....
    ....
      firebase.auth().createUserWithEmailAndPassword(email, password)
          .then(() => {
          ....
        this.writeUserData(uid, name, email, phone);
        navigation.navigate("Profile");
      })
      ....
      .....
  }




但它没有正常使用任何帮助吗?

2 个答案:

答案 0 :(得分:1)

Firebase有许多功能。其中两个是身份验证和实时数据库。

成功致电createUserWithEmailPassword后,它会自动创建用户的UID,并将元数存储在Firebase身份验证中。

现在,您可以在使用firebase.auth(). currentUser.uid进行身份验证后获取此用户的此UID,然后创建要在其中保存数据database.ref().child(path)的firebase参考 使用.set(object).push(object)保存数据。

提示:正确创建数据库体系结构(请参阅文档),以便能够正确获取已保存的数据。

答案 1 :(得分:0)

试试这个,

writeUserData(uid, name, email, phone) {
    const userId = firebase.auth().currentUser.uid;
    
  //You don't have to create key because userId is uniq value.
  return firebase.database().ref(`users/${userId}`).update({name, email, phone});
}

onSignUpPress() {
    ....
    ....
    // createUserWithEmailAndPassword promise resolve return userData!
      firebase.auth().createUserWithEmailAndPassword(email, password)
          .then(userData => {
          ....
        this.writeUserData(userData.uid, name, email, phone);
        navigation.navigate("Profile");
      })
      ....
      .....
  }

我不明白你为什么要尝试更新,

updates['/user-users/' + uid + '/' + newPostKey] = postData;

即使你现在没有postData!

您只需在用户创建帖子数据时设置

writePostData(uid, postData) {
  const postRef = firebase.database().ref(`user-users/${uid}`);
  //this way is useful when key handling before push
  var push =  postRef.push();
  var key = push.key;

  return postRef.child(key).set(postData);
  
  //or just push
  
  return postRef.push(postData);
}