I'm working currently on a side project with react and tmdb api, that in one of it's functionalities, shows a random movie to the user. But since tmdb api doesn't have a random call endpoint, I have to achieve it chaining some api calls where the first one fetches all the available genres and randomize one of it, the second one fetches how many pages there are on that genres and pick one page randomly and the last one fetches the actual movie. I've came up with this solution
export const fetchInitialData = createAsyncThunk(
'randomMovieData/fetchInitialData',
async (_, { rejectWithValue }) => {
try {
//First fetch that gets the available genres
const data = await fetchGenre();
//A function that randomizes a number between 0 and the response length
const randomGenre = randomize(data.genres.length);
//Selecting the random genre
const genre = data.genres[randomGenre].id;
//Second fetch that gets the available movies with that genre
const movie = await fetchPages(genre);
//A function that randomizes a number between 0 and the response length of pages
const randomPage = randomize(movie.total_pages);
//Third fetch that gets all the 20 movies available on the selected page
const movieList = await fetchMovie(genre, randomPage);
//A function that randomizes a number between 0 and the response length
const randomMovie = randomize(movieList.results.length);
const finalMovie = await fetchFinalMovie(
movieList.results[randomMovie].id
);
// console.log(createMovieObject(finalMovie));
console.log(finalMovie);
//Here finally the state is set to the randomly chosen film
return createMovieObject(finalMovie);
} catch (error) {
return rejectWithValue(
`An error occurred. It wasn't possibile to retrieve the requested data`
);
}
}
);
It actually works fine, but I'm wondering if it's the right way of doing it, i mean, chain api calls or if there's a better/correct way.