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)
}
elvezet13
  • 27
  • 1
  • 4
  • 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. – Jayce444 Oct 26 '17 at 12:13
  • In this case, I get TypeError: this.setState is not a function – elvezet13 Oct 26 '17 at 12:22

3 Answers3

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

Raymond_78
  • 86
  • 2
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.

Daniel Andrei
  • 2,654
  • 15
  • 16
  • In this case, I get TypeError: this.setState is not a function. – elvezet13 Oct 26 '17 at 12:22
  • 1
    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}) } – Daniel Andrei Oct 26 '17 at 12:24
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.

shyam
  • 327
  • 2
  • 7