Reputation: 1043
I get the following error when trying to use setState:
Uncaught TypeError: Cannot read property 'setState' of null
I don't know where I am going wrong, could someone point me in the right direction please. Here's my code:
export default React.createClass({
getInitialState: function () {
return {
name: '',
address: '',
phone: '',
email: '',
}
},
componentWillMount(){
this.getUserDetails();
},
getUserDetails: function(){
var personID = 'ABC123';
if(personID.length > 0){
new Firebase('https://xxxxxxxxxx.firebaseio.com/users/' + personID).on('value', function(snap) {
this.setState({
name: snap.val().Name + " " +snap.val().Surname
});
});
}
},
render() {
return ( ... );
}
});
Upvotes: 0
Views: 164
Reputation: 8936
Like people have been saying above, if you just edit this to an arrow function it will change the context of this
from Firebase to the outer scope - which is the component.
new Firebase('https://xxxxxxxxxx.firebaseio.com/users/' + personID).on('value', (snap) => {
this.setState({
name: snap.val().Name + " " +snap.val().Surname
});
});
Upvotes: 2
Reputation: 7308
This is happening because the context of this is not the component anymore. You need this of the component. Check how I grab this of the component.
export default React.createClass({
getInitialState: function () {
return {
name: '',
address: '',
phone: '',
email: '',
}
},
componentWillMount(){
this.getUserDetails();
},
getUserDetails: function(){
var that = this
var personID = 'ABC123';
if(personID.length > 0){
new Firebase('https://xxxxxxxxxx.firebaseio.com/users/' + personID).on('value', function(snap) {
that.setState({
name: snap.val().Name + " " +snap.val().Surname
});
});
}
},
render() {
return ( ... );
}
});
Upvotes: 2