Ad

React.js Cannot Read Property 'setState' Of Undefined

Here is my Profile class :

class Profile extends React.Component {
state={email:'',userName:'',userID:''};
getData()
{
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            {
            console.log(this.responseText);
            this.setState({'userID':JSON.parse(this.responseText).userID});
            console.log(this.responseText);
          Profile.this.setState({userID:JSON.parse(this.responseText).userID});
        }
    };
    request.open('GET', 'http://localhost:8080/user/1');
    request.send();
}
componentWillMount() {
    this.getData()
}
render() {
    return(
<div>
     {this.props.userID}
</div>
    );
}
}
 export default Profile;

It gives me error saying Cannot read property 'setState' of undefined.

Error in line :

Profile.this.setState({userID:JSON.parse(this.responseText).userID});

What's wrong here? How this can be resolved ?

Ad

Answer

There is no Profile.this, Profile is a class, you'll have to keep a reference to the instance or use an arrow function instead of a normal function, the easiest way here will be to keep a reference to the component, here is an example:

getData()
{
    var that = this;
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            {
            console.log(this.responseText);
            that.setState({'userID':JSON.parse(this.responseText).userID});
        }
    };
    request.open('GET', 'http://localhost:8080/user/1');
    request.send();
}

Ad
source: stackoverflow.com
Ad