I'm working with the TMDB API and am having an issue with getting the response to spread into the state in order.
I have 3 lists of which I am mapping over. In each list I have movies of which I am also mapping over to obtain my TMDB ID. From there, I am getting my needed values and setting the state. In an ideal world the state would set in the order that I am calling it with the map functions.
Since the API only allows for 1 ID per request, this was my solution. I know I am missing something obvious here, but any direction on this would be greatly appreciated!
fetchMoviesFromTMDB = async () => {
const TMDb_access_key = TMDB_API_KEY;
await this.props.dashboard.items[0].fields.lists.map(async list =>
list.fields.movies.map(async (movie, index) => {
try {
const tmdbRes = await fetch(
`https://api.themoviedb.org/3/movie/${
movie.fields.tmDbMovieId
}?api_key=${TMDb_access_key}&append_to_response=credits,releases`
);
const TMDB = await tmdbRes.json();
await this.setState({
allMovies: [
...this.state.allMovies,
[
movie.fields.path,
TMDB.poster_path,
movie.fields.movieTitle,
index,
],
],
});
} catch (err) {
console.log(err);
}
})
);
};
You will want to look into Promise.all, which does exactly what you want, executing an array of promises in order.
Simply send your send it your array, and then await it's result if you want to to do any other thing with it :
await Promise.all(this.props.dashboard.items[0].fields.lists.map(async list =>
list.fields.movies.map(async (movie, index) => {
try {
const tmdbRes = await fetch(
`https://api.themoviedb.org/3/movie/${
movie.fields.tmDbMovieId
}?api_key=${TMDb_access_key}&append_to_response=credits,releases`
);
const TMDB = await tmdbRes.json();
await this.setState({
allMovies: [
...this.state.allMovies,
[
movie.fields.path,
TMDB.poster_path,
movie.fields.movieTitle,
index,
],
],
});
} catch (err) {
console.log(err);
}
})
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With