0

I'm building a react app that uses data fetched from an API, but the problem is that I can't seem to display the data properly. Here is how I am reading the API file in my app

fetch(url)
  .then(response => response.json())
  .then(data => {
    if (data) {
      var temp = this.state.ObjectData
      temp.push(data)
      this.setState({ObjectData: temp})
    }            
  })
  .catch(console.log)

And here is what the constructor looks like in my app

constructor(){
  super()
  this.state = {
    ObjectData: []
    }
}

It looks like I'm reading in the API correctly as when I try to use console.log(this.state.ObjectData) I get a '[]' that drops down to '0' and then followed by the first element in the object which for the API file I'm reading would be abilities. But if I do console.log(this.state.ObjectData[0].abilities) I get undefined in the console log

EBjames
  • 11
  • 2
  • What are you trying to get, is it going to return an array and how many times are you trying to make request to the api ? – Qudusayo Oct 26 '20 at 21:05
  • When I read in the API I want to get the object from the JSON file. And then I want out certain elements from the object while making a single fetch request – EBjames Oct 26 '20 at 21:17
  • You could also do `this.setState({ObjectData: [...this.state.ObjectData, ...data]})` Note that in order to get `this.state.ObjectData[0].abilities`, you have to wait until `setState` has completed setting the state, which is an asynchronous process. – Heretic Monkey Oct 26 '20 at 21:17
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Oct 26 '20 at 21:25
  • Tried doing it your way Heretic Monkey, it was able to read in the object but I still can't output any of the data. I can console log ObjectData and it show the empty brackets `[]` with a dropdown to 0 followed by another dropdown to the actual data I want to use – EBjames Oct 26 '20 at 22:09
  • Try to add a sample of response from the API and a sample of the result you need from it – Qudusayo Oct 30 '20 at 01:42

0 Answers0