3
I am trying to access the following variable in the Json of an API:
page[0].infoBloco[0].tabela[0].dados[0].fonte.nome
I’m getting the bug:
TypeError: this.state.page[0] is undefined[Learn More] index.jsx:49
The Json the API returns is as follows:
[
{
"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 code of the React page 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 internal element returns this same error. Would 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 the error TypeError: this.state.page[0] is undefined[Learn More] index.jsx:49
Just do
console.log(page);
, what result does it give? It should not beconsole.log(this.state.page);
?– Leite
this.state.page
returns the full json, fromthis.state.page[0].infoBloco
is that the error appearsTypeError: this.state.page[0] is undefined
– Junior