简体   繁体   中英

React Native Firebase authentication error handling

How to set state ('this.setState({})') inside error handling function for Firebase auth?

its not working in React Native.

  onSignUpPress() {
    if (this.state.password !== this.state.passwordConfirmation ) {
      return this.setState({errorMessage: 'Your passwords do not match'});
    }

      ref.createUser({
        email    : this.state.email,
        password : this.state.password
      }, function(error, authData) {
        if (error) {
            console.log(error);
            // this.setState({errorMsg: error}) <-- Like this, it not work on React Native.
        } else {
            console.log("Successfully created user account with uid:", userData.uid);
        }
    });
  }
});

Try rewriting the function using es6 fat arrow syntax. One issue for sure in the above code is that this is not bound to the correct scope. Try writing the function like this:

onSignUpPress() {
    if (this.state.password !== this.state.passwordConfirmation ) {
      return this.setState({errorMessage: 'Your passwords do not match'});
    }

      ref.createUser({
        email    : this.state.email,
        password : this.state.password
      },(error, authData) => {
        if (error) {
            console.log(error);
            this.setState({errorMsg: error})
        } else {
            console.log("Successfully created user account with uid:", userData.uid);
        }
    });
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM