0

"TypeError: Cannot read property 'state' of null" the above error message is what i get.... following is my code

constructor(props) {
  super(props)
  this.state = {
    desc: '',
  }
}

componentDidMount = () => {
  var ref = fire.database().ref("Employers/Employer1");
  ref.orderByKey().on("child_added", function(snapshot) {

    this.setState({
      desc: snapshot.val()
    })
    console.log('====================================');
    console.log(this.state.desc);
    console.log(snapshot.val().Description);
    console.log('====================================');
  });

  // snapshot.val() is the dictionary with all your keys/values from the '/store' path


}

2 Answers 2

4

This is because of this behavior in javascript. There are two ways to solve it. First to use arrow function, change third line to

ref.orderByKey().on("child_added", (snapshot) => {

other way is to assign value of this to another variable and use state by using that variable. forexample

const self = this;
ref.orderByKey().on("child_added", function(snapshot) {

    this.setState({ desc: snapshot.val() })
    console.log('====================================');
    console.log(self.state.desc);
    console.log(snapshot.val().Description);
    console.log('====================================');
});

For understanding this you can read this article

Sign up to request clarification or add additional context in comments.

1 Comment

If you are satisfied with answer please accept and vote answer
2

componentDidMount is a life cycle hook, it need not be an arrow function.

change

componentDidMount = () => {
}

To

componentDidMount(){
}

Comments

Your Answer

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