Why are arrays inside an object Undefined in the request of the api using Xios?

Asked

Viewed 204 times

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

  • 1

    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

  • 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?

  • That doesn’t make sense. The console.log(typeof api.content) is being executed before or after this.setState({ data: api })?

1 answer

0

Basically, what occurred was an error in passing the data to the state of the React:

 constructor() {
    super();
    this.state = { data: '' };
  }

The fact that the data object was instantiated as a string caused the data to be misinterpreted. I don’t understand the reason, honestly, but I can imagine that maybe it’s something related to dynamic typing. The solution was very simple:

this.state = { data: [] }; // troquei '' para []

Browser other questions tagged

You are not signed in. Login or sign up in order to post.