bobb1213131
bobb1213131

Reputation: 287

Trying to set the state to a value from using a GET in reactjs,

The value is undefined when i console.log it. Trying to fetch data based on the state of a value that isn't null, the dashboardID value should be 1, but its undefined, why?

getDashboardID = _ => {
    fetch(`http://ca-fpscfb2:4000/dashboardID?name=${this.state.Dashboard}`)
    .then(res => res.json())
    .then(res => { 
      this.setState({ dashboardID: res.dashboardID }, () => {
        console.log(this.state.dashboardID)
      })
     })


} 

handleChangeDashboard = (Dashboard) => {
    this.setState({ Dashboard: Dashboard.value });
    this.getDashboardID();

  }

enter image description here enter image description here enter image description here

Upvotes: 0

Views: 41

Answers (2)

Jordan Enev
Jordan Enev

Reputation: 18674

It's because this.setState is async and your response is an Array of objects.

So you can access the value with a callback function and make sure you get the first item in the Array response:

// It's array, so access the first result `res[0].dashboardID`
this.setState({ dashboardID: res[0].dashboardID }, () => {
  console.log(this.state.dashboardID)
})

Also the same idea you have to apply for handleChangeDashboard method, because of the async behavior. Please check @Solo's answer for details.

Please take a look at setState documentation, for further details.

Upvotes: 3

Solo
Solo

Reputation: 6967

// how it is
handleChangeDashboard = (Dashboard) => {
  this.setState({ Dashboard: Dashboard.value });
  this.getDashboardID();
}

// how it should be
handleChangeDashboard = (Dashboard) => {
  this.setState({ Dashboard: Dashboard.value }, () => {
     this.getDashboardID();
  });
}

Why?

fetch(`http://ca-fpscfb2:4000/dashboardID?name=${this.state.Dashboard}`)

this.state.Dashboard could be undefined because setState is not synchronous.

Upvotes: 2

Related Questions