2
I created an api that sends this information:
{
title: 'algum título',
content: ['vários parágrafos']
}
The method that receives the data is as follows:
async componentDidMount() {
let response = await axios.get("http://localhost:8000");
let api = response.data;
this.setState({ data: api });
}
Both the title and content are received correctly, I can view the data by logging, however, the variable type is incorrect.
console.log(typeof api.title) // string
console.log(typeof api.content) // undefined
To solve the case, I use the brackets. This is the only way I can use the map.
<div>
<h1> {this.state.data.title} </h1>
{[this.state.data.content].map(elem => <p> {elem} <br/ > </p>) }
</div>
The point is not that I can’t solve the problem, but I’d like to understand it. Understand why it happens.
From a console.log this.state.data and paste into the question
– novic
Are you sure the API is returning as expected? Beware of spelling errors too, for example, return "cotent" instead of "content". You can check Iss in the "network" tab of Dev Tools
– Costamilam
Can’t this be caused by how the information exits the API? it should come out as Array but is coming out with the information but without Type Defined, its API is of the type that requires type of variables?
– flourigh
That doesn’t make sense. The
console.log(typeof api.content)
is being executed before or afterthis.setState({ data: api })
?– Giovane de Loredo