1

I am very new to react and I am having issues when it comes to passing data from one method to another method. Here is my react syntax:

var url = "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1"
class App extends React.Component{
  info(val){
  console.log(val)
  }

request(){
  axios.get(url)
  .then(function (response) {
      this.info(response)
    console.log(response.data);
  })
  }

render() {
    return(

    <div>
        <h1>axios</h1>
      {this.request()}
      </div>

    )
  }
}

ReactDOM.render(<App />, document.getElementById("target"))

My goal is to pass the response data from request method to info method. However, I am getting error saying that "TypeError: Cannot read property 'info' of undefined" Can you help me identify what I am missing?

1 Answers1

2

Very Common issue and so many answers available for the same, so addition answer as community wiki.

It's a binding issue, you need to bind this with callback.

Use arrow function:

.then( (response) => {

For more details Check this answer: Why is JavaScript bind() necessary?

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142