ashwintastic ashwintastic - 3 months ago 62
React JSX Question

Function call from inside axios then?

How to call a function from inside axios then below is my code which is not working

handleClick(userid){
axios.get(
"http://localhost:4000/user/"+userid+"/items.json")
.then(function (response) {
dispatch(this.buildhtml.bind(response))
})
}


buildhtml(response){
console.log("m called")
}


buildhtml function is not executing !! any idea

Answer

Your code is not working working because your this would be undefined with the current implementation you have.

Can you try this?

handleClick(userid){
  var self=this;
  axios.get(
    "http://localhost:4000/user/"+userid+"/items.json")
    .then(function (response) {
      self.buildhtml.bind(response) // would work
      dispatch(self.buildhtml.bind(response)) //wont work
    })
}

  buildhtml(response){
  console.log("m called")
  }

Now i see above wont work too, even though you change it to self. You are trying to using dispatch. In dispatch you need to pass an action. . Reducers take state and action as parameters and they update state based on what action is passed.

Now an action may return an object or a function. Please go through concepts of redux once. This is not the way an action should be dispatched