【问题标题】:React+Firebase. Write to Database after Authentication反应+火力基地。身份验证后写入数据库
【发布时间】:2017-03-26 15:40:02
【问题描述】:

我目前正在为我的 React Native 应用设置 Firebase。身份验证和基本写入/读取工作正常。 不过,我很难在初始身份验证后立即将数据写入数据库,因为我的“signUp”和“writeUserData”函数同时执行(目前还没有userId)。

这是我的代码:

...

module.exports = React.createClass({
  getInitialState(){
    return({
      email: '',
      password: '',
      confirmPassword: '',
      result: '',
    })
  },

  signUp() {
    if (this.state.password === this.state.confirmPassword) {
      let {email, password} = this.state;
      firebaseApp.auth().createUserWithEmailAndPassword(email, password)
      .catch(error => this.setState({result: error.message
      }));
      this.writeUserData(email);
    } else {
      this.setState({result: 'Passwords do not match.'})
    }
  },

  writeUserData(email) {
    let userId = firebaseApp.auth().currentUser.uid;
    firebase.database().ref('users/' + userId + '/').set({
        info: {
          firstName: 'Jonas',
          email: email,
        },
        currentState: {
          currentDay: 0,
          currentSeries: 0,
        }
    });
  },
  render() {
...

我找不到任何关于此的好的文档。有人可以给我指点吗? 谢谢!

【问题讨论】:

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


    【解决方案1】:

    createUserWithEmailAndPassword() 方法返回 Promise,您必须使用它的 .then 来更新用户详细信息,如下所示:

    firebaseApp.auth()
      .createUserWithEmailAndPassword(email, password)
      .then( user => { 
        user.updateProfile({
            displayName: 'Jonas'
        });
        user.updateEmail(email);
      })
      .catch(error => this.setState({result: error.message}));
    

    还要注意appropriate way 以更新用户的电子邮件

    【讨论】:

    • 谢谢。是的我同意。我最新版本的代码使用.then 方法。它似乎比onAuthStateChanged 更合适、更可靠。
    【解决方案2】:

    我在 Stack Overflow 中找到了解决方案。比预期容易得多:How do you include a username when storing email and password using Firebase (BaaS) in an Android app?

    编辑:我现在改用onAuthStateChanged方法。

      componentDidMount() {
        firebaseApp.auth().onAuthStateChanged(user => {
          if(user) {
            this.writeUserData(user.uid, user.email, this.state.firstName);
          }
        })
      },
    
      writeUserData(userId, email, firstName) {
        firebase.database().ref('users/' + userId + '/').set({
            info: {
              firstName: firstName,
              email: email,
            },
            currentState: {
              currentDay: 0,
              currentSeries: 0,
            }
        });
      },
    

    【讨论】:

      猜你喜欢
      • 2019-01-09
      • 1970-01-01
      • 2021-08-26
      • 2021-06-20
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 2016-09-17
      相关资源
      最近更新 更多