score:5

Accepted answer

you're using function() in your promise chain, this will change the scope for this. if you're using es6 i suggest you use the arrow function to maintain the class scope. example:

you're using

axios.get(app_url, { params: params})
    .then(function(response) { // this resets the scope
       this.setstate({
           videos:response
       })
    })

try using arrow functions:

axios.get(app_url, { params: params})
    .then((response) => {
       this.setstate({
           videos:response
       })
    })

score:0

you can assign the current context this to a variable, also be consistent either use es5 or es6.

apicall(term) {
  const params = {
    part: 'snippet',
    key: app_key,
    q: term,
    type: 'video'
  };
  const _this = this;

  axios.get(app_url, { params: params})
   .then((response) => {
     _this.setstate({
       videos: response
     });
   })
   .catch((error) => {
    console.error(error);
   });
}

score:0

it is due to scoping in your api call. the value of this is different within your response callback in your promise chain. there are two ways to solve this.

you could set a variable referencing this at the beginning of your apicall method.

apicall(term){

    const that = this;

    const params = {
        part: 'snippet',
        key:app_key,
        q:term,
        type: 'video'
    };

   axios.get(app_url, { params: params}).then(function(response) {
       that.setstate({
           videos:response
       });
    }).catch(function(error) {
       console.error(error);
  });

}

or else you can use es6 arrow functions, which maintain the original scope, like this:

axios.get(app_url, { params: params}).then(response => {
    this.setstate({
         videos:response
    });
})

score:0

you also may need to add this.apicall = this.apicall.bind(this) before the this.apicall('surfing'); on your constructor method. this will bind the scope of apicall to the scope of the react component.

more here: https://facebook.github.io/react/docs/handling-events.html

also, remove this.apicall('surfing'); from the constructor and put it into a componentdidmount function, the constructor should not be used for execution.


Related Query

More Query from same tag