0

I am trying to extract data from an external file and populate the items in a component via props. In order to do that I wait for the component to be fully mounted with the componentDidMount() lifecycle method and then process the json data with the map function and eventually set the state.

class ItemComponent extends Component {

  constructor(props) {
    super(props);

    this.state = {
      data: data,
      sections: null
    }
  }

  getItemSections = () => {

    let s = [];

    // Properly logs external data
    console.log(this.state.data);

    s.push(this.state.data.map((section) => {
      return {"slug": section.slug, "name": section.name}
    }));

    // Properly logs processed data.
    console.log(s[0]);

    this.setState({sections: s});

    // Logs `null`.
    console.log(this.state.sections);

  }

  componentDidMount()
  {
    this.getItemSections();
  }

The problem is I am not able to set state with the newly computed data from the external source, not properly anyway and the weird thing is the content is correctly logged everywhere else. What am I doing wrong?

haunted85
  • 1,601
  • 6
  • 24
  • 40
  • 3
    `setState` method is asynchronous, so that can happen try `this.setState({section: s}, () => console.log(this.state.sections))` to ensure that console.log is called after the state has been updated. – Edgar Henriquez Jul 15 '18 at 17:59
  • Why not do it in the constructor? – Tholle Jul 15 '18 at 18:01

1 Answers1

0

The setState() function will not immediately mutate this.state but creates a pending state transition. Refer Here

If you want to wait for the state change to happen and then use the state :

this.setState({variable: <yourvalue> }, function () {
    console.log(this.state);
});
Boo
  • 189
  • 2
  • 8