5

How can i set state inside react component?

I`ve got error message:

Uncaught TypeError: Cannot read property 'setState' of null

here is the component code listing:

class MessageList extends React.Component {
 constructor(props){
 super(props);
 this.state = {
   messages: []
 };

 var firebaseRef = firebase.database().ref();
 firebaseRef.once('value')
  .then(function(dataSnapshot) {
      this.setState({
        messages: messages
      });
   });
 }

 render() { ... }

}
Frank van Puffelen
  • 418,229
  • 62
  • 649
  • 645
Inessa Pokromkina
  • 116
  • 1
  • 2
  • 9
  • Excuse me, @benjamin-gruenbaum , but i meant why i couldnt get data from the firebase, and not about "this" key word – Inessa Pokromkina Aug 28 '16 at 14:20
  • Your bug is because of the `this` keyword. I can either close this as incomplete or as a duplicate - for your sake and the sake of future visitors I think it's better to close this as a duplicate. – Benjamin Gruenbaum Aug 28 '16 at 14:38

2 Answers2

15

this is referring to the promise scope. Either use fat arrow functions (es6)

var firebaseRef = firebase.database().ref();
firebaseRef.once('value')
  .then((dataSnapshot) => {
      this.setState({
        messages: messages
      });
   });

Or create a copy of this before the promise

constructor(props){
 super(props);
 this.state = {
   messages: []
 };
 var that = this; 
 var firebaseRef = firebase.database().ref();
 firebaseRef.once('value')
  .then(function(dataSnapshot) {
      that.setState({
        messages: messages
      });
 });

One last option, you could bind this to the promise:

firebaseRef.once('value')
 .then(function(dataSnapshot) {
     this.setState({
         messages: messages
     });
}).bind(this)
James111
  • 12,551
  • 13
  • 64
  • 104
2

At, first I want to suggest you that you fetch your initial firebase data in componentDidMount component life cycle and to fix your setState issue you can follow the below code in where I've change the self = this; line only,

class MessageList extends React.Component {
 constructor(props){
 super(props);
 this.state = {
   messages: []
 };

componentDidMount() {
 var self = this;
 var firebaseRef = firebase.database().ref();
  firebaseRef.once('value')
  .then(function(dataSnapshot) {
    self.setState({
      messages: messages
    });
  });
 }
}

render() { ... }

}
Md.Estiak Ahmmed
  • 1,353
  • 7
  • 11