1

I want to get data in array from the API but not able to find the exact solution and i am new to React.js I am trying to get the data in temp array from the API but not able to figure it out how to use new state as i am already using one setState in componentDidMount method.

 Code till componentDidMount method:

   class Apiapp extends Component{
      constructor(){
      super()
      this.state = {
        loading:true,
        characters:{}
     }
    }
     componentDidMount(){
         // This means we can use the setState method as many times are we can depending on what 
        type of methods are we using
        // this.setState({
        //   loading:true
        // })
        fetch("https://pokeapi.co/api/v2/pokemon/5")
            .then(response => response.json())
            .then(data => {
             let tmpArray = []
             for (var i = 0; i < data.game_indices.length; i++) {
                tmpArray.push(data.game_indices[i])
             }
              console.log(data)
              this.setState({
              loading:false,
              characters:data
            })
            this.setState({
              loading:false,
              arrCharacters:tmpArray
            })
          })
      }

     Code of render method:

     render() {
      let text = this.state.loading ? <h2>Loading...</h2> : <div><h2> 
                {this.state.characters.name} 

                </h2>,<h2>{this.state.arrCharacters.name}</h2></div>

               // <h2>{this.state.characters.game_indices[0].version.name}</h2>

                return(<div>{text}</div>)
  }
}

I am trying to get all the names that is in "game_indices".

API link: https://pokeapi.co/api/v2/pokemon/ditto

2 Answers 2

1

Don't overcomplicate things

import React, { Component } from 'react';

class ApiApp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      characters: {},
    };
  }

  async componentDidMount() {
    const data = await fetch('https://pokeapi.co/api/v2/pokemon/5').then((response) => response.json());

    this.setState({ characters: data.game_indices, loading: false });
  }

  render() {
    return <div>{this.state.loading ? <h2>Loading...</h2> : this.state.characters.map((i) => i.version.name)}</div>;
  }
}

I'm not too sure what data you are trying to display - its not that clear from the question

Sign up to request clarification or add additional context in comments.

5 Comments

My straight forward question is that i want to display list of names that are in this link " pokeapi.co/api/v2/pokemon/ditto" names are blue,gold, ruby and so on. please see the API i want to diplay game_indices":[{"game_index":76,"version":{"name":"red" ==> these names i want ot get in list.
@nitinbakaya answer updated. You need to use i.version.name
Your code is just showing Loading.... no data. I think that you missed something.
@nitinbakaya you are correct - I forgot to set loading to false.. I have updated the answer
Thanks a lot for sharing the easy and much more concise solution than the first one posted by other Guy.
1

There are cleaner ways to achieve the same result. However, I'd rather explain what it is wrong with your code:

Check the comments below in your code

import { Component } from 'react'

class App extends Component {
  constructor() {
    super()
    this.state = {
      loading: true,
      characters: {},
    }
  }
  componentDidMount() {
    this.setState({
      loading: true,
    })
    fetch('https://pokeapi.co/api/v2/pokemon/5')
      .then((response) => response.json())
      .then((data) => {
        let tmpArray = []
        for (var i = 0; i < data.game_indices.length; i++) {
          tmpArray.push(data.game_indices[i])
        }
        this.setState({
          loading: false,
          characters: data,
        })
        this.setState({
          loading: false,
          arrCharacters: tmpArray,
        })
      })
  }

  //  Code of render method:

  render() {
    let text = this.state.loading ? (
      <h2>Loading...</h2>
    ) : (
      <div>
        <h2>{this.state.characters.name}</h2>,
        {/* 1 - When the page first loads "arrCharacters" is undefined. 
          Therefore you need to add a condition to make sure it is not undefined.
          2- You need to loop through all elements to display the name for each of them. 
          For that, you can use the js array method map.
          3- When you display a list, you must use a unique key as  attribute. 
          4 - After you need to check where the data you want to display lives. 
          In your case, it is inside an obj version. So you access it with "." or "[]"
*/}
        {this.state.arrCharacters &&
          this.state.arrCharacters.map((char) => (
            <h2 key={char.version.name}>{char.version.name}</h2>
          ))}
      </div>
    )

    return <div>{text}</div>
  }
}

export default App

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.