I'm trying to learn the basics of a full stack React app and I'm running into a really weird issue with my API calls.
I want to retrieve a list of trailers from a database that get returned as an array of objects. I then use a promise to loop over that array, and make a separate API call on to each item in the array to add a key value pair to the object. After I've built that array of objects, I set it to my app state, then pass it down through a prop to the child component that should render a list of elements based on the info in the array.
Right now, the console logs the array the component receives and all the data is present, however, every field can be rendered except the one that is added within the forEach loop.
I have removed the API call from the forEach loop, and instead just set a static value in the loop, and the information gets rendered properly as expected. So I'm sure the issue is with the API call being in the loop. I can't figure out why though. The log shows that array is complete, so it doesn't seem to make sense that the render can't find the data.
// The API call
loadUserAndTrailers = () => {
let trailers = [];
axios.get("http://localhost:5000/api/trailers")
.then (res => {
trailers = res.data;
})
.then (() => {
trailers.forEach(trailer => {
axios.get(`http://localhost:5000/api/votes/user/${this.state.user.id}/${trailer.TrailerID}`)
.then (res => {
const vote = res.data[0].Vote;
trailer.vote = vote;
})
})
})
.then (() => {
this.setState({trailers: trailers});
})
}
// The child component
const TrailerList = props => {
console.log(props)
const trailers = props.trailers.map(trailer => {
return <div>{trailer.vote}</div>
});
return <div>{trailers}</div>;
};
// The return in the parent component
return (
<div className="container">
<div className="content">
<h1>Trailers</h1>
<div className="trailers">
<TrailerList trailers={this.state.trailers}></TrailerList>
</div>
</div>
</div>
);
The console.log(props) shows me a completed array with an array of objects with this key value existing { vote: 1 } yet it renders nothing. How can this be? I've been slamming my head against a wall for two days now, but I'm admittedly new to APIs and promises. I was under the impression the promise should make sure the call is completed before moving on to the next step, and my properly logged state seems to imply that that aspect of the code is functioning as expected.