I'm getting a json from an endpoint which looks like this:
{"section":{"name":"name","subsections":[
{"name":"one","snippets":[{"title":"title","body":"body"}]},
{"name":"two","snippets":[{"title":"title","body":"body"}]}]
}}
This is how I get the data:
fetchData() {
axios.get('/api/data')
.then(response => {
this.setState({
section: response.data.section
})
})
.catch(error => {
console.log(error);
});
}
componentDidMount() {
this.fetchData();
}
But when I call this.state.section.subsections[0]
I get the following error:
Uncaught TypeError: Cannot read property '0' of undefined
I know that the subsections
is an array, but on getting the elements from it. I get an error. Would anyone know what I might be doing wrong?
Edit:
I want to access the state in the render method. I can access this.state.section.name
, I can also print this.state.section.subsections
on the console. But whenever I try to access the elements using this.state.section.subsections[0]
I get an error.