0

I am trying to make a program that will just display a certain pokemons name and get a picture using Pokeapi. But it appears that after my pokeURL variable is out of the $.getJSON function, it resets itself back to null.

import React from "react"
import $ from "jquery"

class Pokemon extends React.Component{
    constructor(props){

        super()
        this.state = {
            imageUrl: ""
        }

    }
    componentDidMount() {
        let pokeURL
        this.setState(()=>{
            $.getJSON("https://pokeapi.co/api/v2/pokemon/" + (this.props.pokemon).toLowerCase() + "/", function(data){
                pokeURL = data.sprites.front_default;
                // console.log(pokeURL)
                // console.log(data)    
            })
            // console.log(pokeURL)
            return {
                imageUrl: pokeURL
            }
        })  


    }
    render(){
        return(
            <div>
                <h1>{this.props.pokemon}</h1>
                <img src={this.state.imageUrl} height = "400px" width = "400px"/>
            </div>
        )
    }
}
export default Pokemon

I looked at my console, and I am receiving the pokemon api call fine, but it just doesn't save to a variable. I have tried using a let and just setting it to a global variable but it seems to just reset. Note: Props only has a pokemon string in it which is the name of what I want to draw.

  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – JJJ Aug 16 '19 at 05:01

1 Answers1

1

Try this :

$.getJSON("https://pokeapi.co/api/v2/pokemon/" + (this.props.pokemon).toLowerCase() + "/", function(data){
    this.setState({
        imageUrl : data.sprites.front_default;
    })
})
Sagar
  • 1,374
  • 10
  • 18
  • componentDidMount() { $.getJSON("https://pokeapi.co/api/v2/pokemon/" + (this.props.pokemon).toLowerCase() + "/", function(data){ this.setState({ imageUrl : data.sprites.front_default }) }) When I put that in I got a TypeError: this.setState is not a function error – Alex Tsang Aug 16 '19 at 04:55
  • 1
    @AlexTsang Use arrow function, `(data) => {` which binds `this`. – ravibagul91 Aug 16 '19 at 05:04
  • That fixed the problem. Thanks a ton. :) – Alex Tsang Aug 16 '19 at 05:10