I am attempting to fetch data from this NHL API: https://statsapi.web.nhl.com/api/v1/people/8477474/
When I output the call to my page it returns undefined and I can't get it to display the value. Oddly enough, the first element in the object displays correctly but not any of the nested elements.
Here is my code:
import React, {Component} from "react"
class App extends Component {
constructor() {
super()
this.state = {
loading: false,
player: {}
}
}
componentDidMount() {
this.setState({loading: true})
fetch("https://statsapi.web.nhl.com/api/v1/people/8477474/")
.then(response => response.json())
.then(data => {
this.setState({
loading: false,
player: data
})
})
}
render() {
const fullname = this.state.loading ? "Loading..." : this.state.player.people[0].fullName;
return (
<div>
{fullname }
</div>
)
}
}
export default App
This is not supposed to return undefined, because the key value is clearly there and I believe I am targeting it right.
I tried console logging but I also get undefined.
I tried as well removing the [0] and doing this.state.player.people.fullName and all kinds of alternatives but no luck.
Set the initial state of loading to true, and remove the line this.setState({loading: true}).
There is a small amount of time where loading is false and the data isn't in player yet. Try the below
const fullname = Object.keys(this.state.player).length ? this.state.player.people[0].fullName:""
return (
<div>
{this.state.loading ? "Loading....": fullname }
</div>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With