Jon Nicholson
Jon Nicholson

Reputation: 1131

Attempting to render Firebase Auth user details through this.setState in React app undefined

I am attempting to render a User's details through Firebase Auth on a 'Profile' page, for them to update if they wish.

I'm attempting to do this within 'componentDidMount', so on page load, using state. However, the function I'm attempting to run is returning the 'this.setState' call as 'undefined'.

This is the error message:

Unhandled Rejection (TypeError): undefined is not an object (evaluating 'this.setState')

Is there a way to refactor my code to render on page load using firebase.auth.onAuthStateChanged?

Here's my component code:

class Profile extends Component {
  constructor(props) {
    super(props)

  this.state = {
    displayName: "",
    email: ""
  }
}

  componentDidMount() {

    firebase.auth().onAuthStateChanged(function(user) {
    if (!user) {
      this.setState({
        displayName: "",
        email: ""
      })
    } else {
        this.setState({
          displayName: user.displayName,
          email: user.email
        })
    }
  });

  }

onChange = (e) => {
      this.setState({ [e.target.name]: e.target.value})
  }

  render() {

    return (
              <input className="profile-info-type" type="text" name="displayName" value={this.state.displayName || ''} onChange={this.onChange} />

                <input className="profile-info-type" type="email" name="email" value={this.state.email || ''} onChange={this.onChange} />

    )
  }
}

Any pointers would be appreciated!

Upvotes: 0

Views: 113

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

You should use an arrow function for your callback, which will preserve the value of this in the outer scope.

firebase.auth().onAuthStateChanged(user => {
    // this.setState()
})

Upvotes: 1

Related Questions