snowleopardAlexa
snowleopardAlexa

Reputation: 19

Access nested array value inside other array in the stateful ReactJS component

I am trying to call data in the react app from fake Postman API, and so far it works well when I call from a single array of objects:

{
   "animals": [
 {
      "id": 1,
      "name": "Tiger",
      "diet": "Carnivore",
      "habitant": "Asia",
      "lfespan": "1-15 years"
 },
  {
      "id": 2,
      "name": "Lion",
      "diet": "Carnivore",
      "habitant": "Africa",
      "lfespan": "1-15 years"
  },
 ]
}

App.js

class App extends React.Component {
  state = {
   animals: []
}
// arrow function - no need to bind
getAnimal = async (e) => {
 const animalName = e.target.elements.animalName.value;
   e.preventDefault();
   const api_call = await fetch(`https://4ab06793-05d5-47b8-b3cb- 
   56c26a95e5d4.mock.pstmn.io/animals`)

 const data = await api_call.json();
   this.setState({animals: data.animals});
    console.log(this.state.animals)
}

However, my data does not display on the screen when I try to call the data from categories: wildCats, birds. I just don't know how to do it. I am pretty sure this is super-easy, but I am a beginner and I could not find the answer anywhere. What I tried to do, and it did not work out:

 App.js

 class App extends React.Component {
 state = {
  animals: [
   {
     wildCats: []
   }
  ]
 }
 // arrow function - no need to bind
 getAnimal = async (e) => {
 const animalName = e.target.elements.animalName.value;
 e.preventDefault();
 const api_call = await fetch(`https://4ab06793-05d5-47b8-b3cb- 
 56c26a95e5d4.mock.pstmn.io/animals`)

 const data = await api_call.json();
 this.setState({animals: data.animals.wildCats});
 console.log(this.state.animals.wildCats)
 }

JSON file

{
 "animals": [
 { 
  "wildCats": [
    {
      "id": 1,
      "name": "Tiger",
      "diet": "Carnivore",
      "habitant": "Asia",
      "lfespan": "1-15 years"
    },
    {
      "id": 2,
      "name": "Lion",
      "diet": "Carnivore",
      "habitant": "Africa",
      "lfespan": "1-13 years"
    },
    {
      "id": 3,
      "name": "Leopard",
      "diet": "Carnivore",
      "habitant": "Africa, South America",
      "lfespan": "1-12 years"
    }
  ],
  "birds": [
    {
      "id": 4,
      "name": "Macaw",
      "diet": "Herbivore",
      "habitant": "South America",
      "lfespan": "1-70 years"
    },
   ]
  }
 ]
}

Upvotes: 0

Views: 39

Answers (1)

Naren
Naren

Reputation: 4470

Try this, as data.animals is an data.animalsArray, you should getting the data with index.

 const data = await api_call.json();
 this.setState({ animals: data.animals[0].wildCats });

 or 
 this.setState({ animals: data.animals[0].birds });

Upvotes: 2

Related Questions