I'm trying to access the following Json variable in an API:
page[0].infoBloco[0].tabela[0].dados[0].fonte.nome
I'm getting the error:
TypeError: this.state.page[0] is undefined[Learn More] index.jsx:49
The Json API returns:
[
{
"infoBloco": [
{
"tabela": [
{
"dados": [
{
"fonte": {
"url": "http://www.google.com",
"nome": "Site de buscas"
}
}
]
}
]
}
]
},
{
"infoBloco": [
{
"tabela": [
{
"dados": [
{
"fonte": {
"url": "http://www.yahoo.com",
"nome": "Outro site de buscas"
}
}
]
}
]
}
]
}
]
The React page code is as follows:
import React, { Component } from "react"
export default class extends Component {
constructor(props) {
super(props)
this.state = {
page: [],
}
}
componentDidMount() {
this.getData()
}
getData = async () => {
await fetch('http://localhost:3003/api')
.then(resp => resp.json())
.then(data => this.setState({
...this.state,
page: data,
}))
}
render() {
console.log(this.state.page[0].infoBloco[0].tabela[0].dados[0].fonte.nome)
return (
<div>
Exemplo
</div>
)
}
}
I can only access up to page [0], when I try to access any more inner element it returns that same error. Could this error be caused by asynchronous access to the API? Can anyone help me fix this?
console.log(this.state.page)
returns the full json
console.log(this.state.page[0])
returns the first json object
console.log(this.state.page[0].infoBloco)
generates error TypeError: this.state.page[0] is undefined[Learn More] index.jsx:49