-1

I try to setState after a firebase call in componentDidMount:

class Profile extends Component {

constructor(props) {
    super(props)
    this.state = {
        nick: this.props.match.params.user,
        nickid: this.props.match.params.id,
        nickuid: null
    }
}

componentDidMount() {

    firebase.database().ref('/users/').orderByChild('user').equalTo(this.props.match.params.user).once('value').then(function(snapshot) {
      var uid = Object.keys(snapshot.val())[0];
      this.setState({ nickuid: uid }); // error (uid is not null)
      console.log(uid);
    });

}

I get Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined any ideas why?

RGS
  • 4,062
  • 4
  • 31
  • 67
  • 1
    That's because you're using a `function`, that creates a new `this` context. Your `.then()` function won't have a setState property on it. So there's a few ways to solve this: 1. Use arrow functions. If you use arrow functions (i.e. `.then((snapshot) => {})`, then `this` will be the context of the `componentDidMount` function of a React.Component, which contains the `setState` function. 2. Bind the context of the React lifecycle to your `function`: `.then(function(snapshot) {}.bind(this))` – Alserda May 06 '20 at 12:36

2 Answers2

3

Use arrow function here. You have lost the context when passed function Try:

.then(snapshot => {
   ...
Mark Partola
  • 654
  • 3
  • 10
1

Use arrow function.

.once('value').then((snapshot) => {
      var uid = Object.keys(snapshot.val())[0];
      this.setState({ nickuid: uid });
      console.log(uid);
    });
hackape
  • 18,643
  • 2
  • 29
  • 57