1

I'm running this code in my react app:

  componentDidMount() {
    modelInstance.addObserver(this);
    modelInstance.getSignInStatus().then((user)=>{
      this.setState({
        userName: user !== false ? user.displayName : "Sign in",
        logged_in: user !== false ? true : false

      });
    });
  }

And here is modelInstance.getSignInStatus():

  this.getSignInStatus = function () {
    return new Promise((resolve, reject)=>{
      firebase.auth().onAuthStateChanged(function(user){
        if (user){
          resolve(user);
        }
        else {
          resolve(false);
        }
      });
    });
  }

What happens is that this.state.userName is set to null, meaning that user.displayName is null. Why is this?

2 Answers 2

1
  state = {
    username: "",
    email: "",
    passwordOne: "",
    passwordTwo: "",
    error: null
  }; 

  onSubmit = event => {
    const {username, email, passwordOne} = this.state;
    const {history} = this.props;

    auth
      .createUserWithEmailAndPassword(email, password);
      .then(authUser => {
        db.doCreateUser(authUser.uid, username, email).then(() => {
          //you should clear your state fields here, for username / email etc
          console.log(authUser);
          //redirect user
          history.push(routes.HOME);
        });
      })
      .catch(error => {
        this.setState({error});
      });
    event.preventDefault();
  };

const auth = firebase.auth();

const db = firebase.database(); in order to acess doCreateUser

const doCreateUser = (id, username, email) =>
  db.ref(`users/${id}`).set({
    uid:id,
    username,
    email,
  });
Sign up to request clarification or add additional context in comments.

Comments

0

I would use setState for checking the auth status like so:

firebase.auth().onAuthStateChanged(function(user){
    if (user){
      this.setState({user});
    }
}

Then you want the state of the displayName of the current user

componentDidMount() {
 modelInstance.addObserver(this);
 modelInstance.getSignInStatus().then((user)=>{
   this.setState({
     userName: this.state.user ? this.state.user.displayName : "Sign in",
     logged_in: this.state.user ? true : false
   });
 });
}

Obviously there has to be a name in the displayName property, If not you would have to update it. Let me know how this turns out.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.