Reactjs and Pokeapi JSON

I'm new to React and handling JSON but i've read a lot here. So i've been trying to pass the JSON which I get from the pokeapi into variables here is what i've got so far:

getPokemons=(id)=> {

    return fetch(`https://pokeapi.co/api/v2/pokemon/${id}/`)
      .then(res => {
        if (res.ok) {
          //return res.json()
         console.log(res.json())


        }
     })
   }

I tried this method: Return json object to render method - React.js but didn't work

728x90

2 Answers Reactjs and Pokeapi JSON

You need to do something like below

     getPokemons=(id)=> {
       fetch(`https://pokeapi.co/api/v2/pokemon/${id}/`)
          .then(res => res.json())
          .then(data => {
               this.setState({data}); //here you are setting data to data state variable 
          })
         .catch(err => {
             console.log(err);
         });
     }

4 months ago

You will need to make the API result part of the state by using setState. Try out this component by copying it into your code:

class PokemonFinder extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  
  getPokemon(id) {
    fetch(`https://pokeapi.co/api/v2/pokemon/${id}/`)
      .then(results => results.json())
      .then(data => {
        this.setState({data});
      });
  }
  
  render() {
    return <div>
      <input value={this.state.id} 
        onChange={(ev) => this.setState({
          value: ev.target.value
        })}
      />
      <button onClick={() => this.getPokemon(this.state.id)}>Get Pokemon</button>
      <div>{JSON.stringify(this.state.data, null, 2)}</div>
    </div>;
  }
}

ReactDOM.render(<PokemonFinder/>, document.getElementById('app'));
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>

<div id="app"></div>

4 months ago