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?