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() { ... }
}
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)
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() { ... }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With