Reputation: 206
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.
Upvotes: 3
Views: 799
Reputation: 113
You could initiate player state to null. Then use this line.
const fullname = this.state.player ? this.state.player.people[0].fullName:""
Or you could also do this with React Hooks if you wanted to as well.
https://codesandbox.io/s/baseball-fetch-api-30ehh?file=/src/App.js
import React, { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
const [loading, setLoading] = useState(true);
const [player, setPlayer] = useState();
useEffect(() => {
const fetchPeople = async () => {
await fetch("https://statsapi.web.nhl.com/api/v1/people/8477474/")
.then((res) => res.json())
.then((res) => setPlayer(res))
.then(() => setLoading(false))
.catch((err) => setLoading(err));
};
fetchPeople();
}, []);
console.log(player);
const fullname = player ? player.people[0].fullName : "";
return <div className="App">{loading ? "Loading...." : fullname}</div>;
}
Upvotes: 0
Reputation: 4264
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>
)
Upvotes: 1
Reputation: 1352
Set the initial state of loading to true
, and remove the line this.setState({loading: true})
.
Upvotes: 2