1

I'm currently setting up Firebase for my React Native app. Authentication & basic writing/reading work fine. Though, I struggle to write data to the database right after the initial authentication because my "signUp" and "writeUserData" functions execute at the same time (and at this moment there is no userId yet).

Here is my code:

...

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() {
...

I can't find any good documentation about this. Can someone give me a pointer? Thanks!

mkj
  • 2,761
  • 5
  • 24
  • 28
Jonas
  • 355
  • 1
  • 4
  • 16

2 Answers2

2

The createUserWithEmailAndPassword() method returns Promise, you have to use it's .then for updating the user details, like this:

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

Note also the appropriate way to update user' email

Ivan Chernykh
  • 41,617
  • 13
  • 134
  • 146
  • Thanks. Yes, I agree. I my latest version of the code uses a `.then` method. It seems more appropriate & reliable than `onAuthStateChanged`. – Jonas Dec 04 '16 at 04:42
1

I found the solution within Stack Overflow. Much easier than expected: How do you include a username when storing email and password using Firebase (BaaS) in an Android app?

EDIT: I'm using now the onAuthStateChangedmethod instead.

  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,
        }
    });
  },
Community
  • 1
  • 1
Jonas
  • 355
  • 1
  • 4
  • 16