I'm creating an app in React and I am having issues with my state change not updating the DOM. I'm pulling data asynchronously from my API in a function and calling it in componentDidMount. I have componentDidMount marked as async and am awaiting the response. However, this never seems to actually update the state.
What's suppose to happen (as far as I know) is after the state is updated, React should update the UI with the new data pulled from the server. No errors get logged, instead, simply nothing happens.
Here is my componentDidMount function and getMovieStacks function:
async componentDidMount() {
const stacks = await this.getMovieStacks();
console.log(stacks); // -- IN PICTURE --
this.setState({ stacks });
}
async getMovieStacks() {
const stacks = [];
// get genres
const res = await fetch("http://localhost:5000/api/genres");
const genres = await res.json();
// foreach genre, get movies
genres.forEach(async (genre) => {
const id = genre._id;
const res = await fetch(`http://localhost:5000/api/movies/genre/${id}`);
const movies = await res.json();
stacks.push({ id: id, genre: genre.name, movies: movies });
});
return stacks;
}
The console.log in componentDidMount results in this structure, which is what I want.
Then, in the render function I have this:
render() {
return (
<div className="App">
<Header />
{this.state.stacks.map((stack, index) => {
console.log(stack);
return (
<MovieStack key={index} genre={stack.genre}>
{stack.movies.map((movie, index) => {
return <MovieCard key={index} movie={movie} />;
})}
</MovieStack>
);
})}
</div>
);
}
I'm at a loss as to what I'm missing here. Stacks is correctly being returned, and the state is being set, but the DOM never gets re-rendered.