In this React component, I am trying to set an object as the URL for the Img
's src
. However, I kept getting the error: TypeError: Cannot read property 'front_default' of undefined (/App.js:33)
. This is in a Scrimba course
import React, {Component} from "react"
class App extends Component {
constructor() {
super()
this.state = {
loading: false,
character: {}
}
}
componentDidMount() {
this.setState({loading: true})
fetch("https://pokeapi.co/api/v2/pokemon-form/1")
.then(response => response.json())
.then(data => {
this.setState({
loading: false,
character: data
})
console.log(this.state.character.name)
console.log(this.state.character.sprites.front_default)
})
}
render() {
const text = this.state.loading ? "loading..." : this.state.character.name
let frontSprite = this.state.loading ? "Loading..." : this.state.character.sprites.front_default
// The url that the img should get: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/1.png"
return (
<div>
<img src={frontSprite}/>
<p>{text}</p>
<p>{frontSprite}</p>
</div>
)
}
}
export default App
The solution was to create a new state called front_default
, which will store the url of this.state.character.sprites.front_default
. After the data is fetched, front_default
equaled to whatever the URL was.
import React, {Component} from "react"
class App extends Component {
constructor() {
super()
this.state = {
loading: false,
character: {},
front_default: "",
}
}
componentDidMount() {
this.setState({loading: true})
fetch("https://pokeapi.co/api/v2/pokemon-form/1")
.then(response => response.json())
.then(data => {
this.setState({
loading: false,
character: data,
front_default: data.sprites.front_default
})
console.log(this.state.character.name)
})
}
render() {
const text = this.state.loading ? "loading..." : this.state.character.name
let frontSprite = this.state.loading ? "Loading..." : this.state.front_default
// The url that the img should get: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/1.png"
return (
<div>
<img src={frontSprite}/>
<p>{text}</p>
<p>{frontSprite}</p>
</div>
)
}
}
export default App