Nauman Ahmad Nauman Ahmad - 4 months ago 21
React JSX Question

Update state through an ajax request but state is still undefined

I am updating a state through an ajax request to the server. I am receiving data from the server but the state doesn't update for some reason and shows up as undefined when I try to iterate the array.

class TodoList extends Component {
constructor(props) {
super(props);
this.state = {
data: undefined
}
}

componentWillMount() {
request
.get('http://localhost:8080/api/todo')
.end(function(err, res) {
this.setState({data: res});
}.bind(this));
}

render() {
return (
<div>
<h1>Todo Items</h1>
<ul>
{this.states.data.map((item) => {
return <li>item.data</li>
})}
</ul>
</div>
);
}
}


Console Logs

Uncaught TypeError: Cannot read property 'data' of undefined
Uncaught TypeError: Cannot read property '_currentElement' of null

Answer

First of all, you have a typo, change:

{this.states.data.map((item) => {
  return <li>item.data</li>
})}

To:

{this.state.data.map((item) => {
  return <li>item.data</li>
})}

Also, before your data is fetched, state.data is undefinded and it has no method .map().
Change it to an empty array:

constructor(props) {
  super(props);
  this.state = {
    data: undefined
  }
}

to:

constructor(props) {
  super(props);
    this.state = {
      data: []
  }
}