reactjs - React: cannot get properties from state -
i have react app , having difficulty drilling state.
import react, { component } 'react'; import { grid} 'react-bootstrap' import fetch 'isomorphic-fetch'; class pokemon extends component { constructor(props) { super(props); this.state = { pokemon: {}, } } componentdidmount() { fetch('https://pokeapi.co/api/v2/pokemon/150/') .then((response) => { return response.json() }) .then((json) => { this.setstate({ pokemon: json, }) }) } render () { const { pokemon } = this.state console.log(pokemon.species) // works return ( <grid> <p>{pokemon.species.name}</p> <image src={this.props.image} responsive alt='member picture' /> </grid> ) } } export default pokemon; using react developer tools can see data in state.
i can perform
console.log(pokemon.species) which return object 2 properties url & name. when try
console.log(pokemon.species.name) it returns "typeerror: pokemon.species undefined"
in state state = { pokemon: {} }, state looks this.
looks have no pokemon.species before api responds. try this:
constructor(props) { super(props); this.state = { pokemon: {species:{}}, } } 
Comments
Post a Comment