Mohi Indharan Mohi Indharan - 2 months ago 13
Ajax Question

how to set state with reponse ajax request in reactjs

I bind and used this still getting this error ,did the same thing for
another it worked perfect when did the same here, But I'm getting a error.

class Player extends React.Component{
constructor(){
super();
this.setState={
video:{}
};
}

componentDidMount () {
var sess=localStorage.getItem('sessionId');
var id=this.props.params.vid;



local ajax request console log shows my request is good


$.ajax({
method:'GET',
url:'video',
data:{
'sessionId':sess,
'videoId':id
},
success:function(res){
this.setState({ video:res.data })
}.bind(this)
});
}
render(){

return(

<div id="videoplay">
<div className="video-title"></div>
<video controls src="/images/Google_Cardboard_Assembly.mp4">
</video>
<div className="video-metadata">

<div className="video-rating"></div>
<div className="video-description"></div>

</div>
</div>
);
}

}


error

Uncaught TypeError: this.setState is not a function

Answer

in the constructor, you just need to do this.state = { video: {} } not this.setState

constructor(){
    super();
    this.state = {
        video:{}
    };
}

this.setState can be used anywhere else but the constructor. non es6 way of doing this was doing:

getInitialState: function() {
  return { 
    video: {}
  }
}

which is equivalent to just doing this.state = {} in the constructor