I am making a simple React site which fetches some data from an API (this API) and then display it on the page. The endpoint I am using is the skyblock/auctions endpoint. What this returns is a list of objects, which I want to get the first one of and then pass it to a child component. The parent can successfully get the data, however when I pass it to the child and console.log it, it returns null. The only reason I can think of for why its doing this is because the parent component hasn't finished fetching the data yet, but I am not sure how to make it render only after its finished.
Here is the code for the parent component AuctionViewer:
class AuctionViewer extends Component {
state = { data: null}
loadData = async () => {
let url = "https://api.hypixel.net/skyblock/auctions?key=INSERT_KET_HERE"
let response = await fetch(url);
let json = await response.json();
this.setState({data: json.auctions[0]}, function () {
console.log(this.state.data)
});
}
componentDidMount() {
this.loadData();
setInterval(this.loadData, 60 * 1000);
}
render() {
return (<Auction data={this.state.data} />);
}
}
And here is the child component Auction:
class Auction extends Component {
state = {
loading: true,
item: null,
price: null,
startPrice: null,
time: null,
};
loadData() {
let data = this.props.data;
console.log(data);
let end = new Date(data.end - Date.now());
let timeLeft = end.getHours() + ":" + end.getMinutes() + ":" + end.getSeconds();
this.setState({loading: false, item: data.item_name, price: data.highest_bid_amount, startPrice: data.starting_bid, time: timeLeft, timestamp: end});
};
componentDidMount() {
this.loadData();
}
render() {
return (
<div className="gridBox">
{this.state.loading ? (
<p>Loading...</p>
) : (
<div>
<p>Item: {this.state.item}</p>
<p>Top Bid: {this.state.price}</p>
<p>Start Bid: {this.state.startPrice}</p>
<p>Time Left: {this.state.time}</p>
</div>
)}
<button onClick={this.loadData}>Refresh</button>
</div>
);
}
}