1

I have a handler that fires upon change in the input field. However, when I log the state to the console resData is 'undefined'? It's impossible because console.log(body) does return results.

handlePersonNameChange(event) {
var resData
request('https://swapi.co/api/people/?search='+event.target.value, function (error,response,body) {
  console.log(body)
  resData = body
})
this.setState({personData: resData});
console.log(this.state)
}
2
  • You should set the state inside the request callback. Also, setting state in React is asynchronous, so you can't setState() then console.log(this.state) on the next line and expect to see the state updated. Commented Oct 26, 2017 at 12:13
  • In this case, I get TypeError: this.setState is not a function Commented Oct 26, 2017 at 12:22

3 Answers 3

5

A request call is asynchrone, you should put the this.setState within the response body.

Also this.setState is asynchrone, to see the result you should use the callback function. This funciton is called after the new state is set.

handlePersonNameChange(event) {
  var resData
  request('https://swapi.co/api/people/?search='+event.target.value, 
  function (error,response,body) {
    console.log(body)
    resData = body
    this.setState({personData: resData}, function() {
      console.log(this.state)
    })
  })
}

More info about this.setState() can be found here

Sign up to request clarification or add additional context in comments.

Comments

1

You need to setState inside the request callback, for example :

request('https://swapi.co/api/people/?search='+event.target.value, function (error,response,body) {
  console.log(body)
  resData = body
  this.setState({personData: resData});
})

because your request hasn't resovled when you do setState in your example.

2 Comments

In this case, I get TypeError: this.setState is not a function.
That's because your callback isn't binded. You can use an arrow function (if you have ES6 support) (error, response, body) => { this.setState({personData: body}) }
0
this.setState({ state : "new1" })

This method is not synchronous so when you are logging the state it is not yet updated.

You should log it in componentWillUpdate lifecycle method.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.