how to set state with reponse ajax request in reactjs

Question!

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


Answers

You can use the React lifecycle methods to make your request.

Example

class YourClass extends Component {
  constructor () {
    super();
    this.state = {
      video: {}
    };
  }

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

  render () {
    return ( /* ... your render method ... */ );
  }
}


You need to modify your constructor method from:

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

to:

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

Also, I think this in this.setState() call does not refer to your Class in $.ajax() call. Try binding both: the ajax() call and the success() function or use the arrow function for your success() method.



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

By : finalfreq


This video can help you solving your question :)
By: admin