ashwintastic
ashwintastic

Reputation: 2312

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

Upvotes: 7

Views: 21664

Answers (2)

guru_007
guru_007

Reputation: 473

When using Vue.js with axios ,I too had this Issue but , this is how I solved it.

let vue = new Vue({
 el:#<element>,
 methods:{

  method1()
  {
 axios.post('<url>',{<data>})
 .then( ( res ) => {
  this.method2(res)  // method call to method2 
  } )
 .catch( ( err ) => { <call> } );     
  },//method1 end

method2(res){
// statements
} 

}
});

Refer this.

Upvotes: 6

Harkirat Saluja
Harkirat Saluja

Reputation: 8124

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

Upvotes: 12

Related Questions