Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setState with Firebase Promise in React [duplicate]

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() { ... }

}
like image 757
Inessa Pokromkina Avatar asked Aug 28 '16 11:08

Inessa Pokromkina


2 Answers

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)
like image 152
James111 Avatar answered Oct 21 '22 04:10

James111


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() { ... }

}
like image 2
Md.Estiak Ahmmed Avatar answered Oct 21 '22 04:10

Md.Estiak Ahmmed