5

The React docs say I should make AJAX calls to set the state in componentDidMount(), not the constructor. According to all the examples I have seen, this is how I should load data from the server:

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

componentDidMount() {
    loadToDoItems()
        .then(items => this.setState({toDoItems: items}));
}

Why not just load the server data in the constructor, like this?:

constructor() {
    super();
    loadToDoItems()
        .then(items => this.state = {toDoItems: items});
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143

0 Answers0