Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching from API endpoint with React returns value undefined

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.

like image 553
Uriel Avatar asked Mar 10 '26 08:03

Uriel


2 Answers

Set the initial state of loading to true, and remove the line this.setState({loading: true}).

like image 153
codemax Avatar answered Mar 12 '26 23:03

codemax


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> 
)
like image 32
ak85 Avatar answered Mar 12 '26 22:03

ak85



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!