0

i have the following function:

const getTotalPages = async () => {
  const selectedGenre = getSelectedGenre();
  const discoverMovieEndpoint = '/discover/movie';
  const requestParams =`api_key=${tmdbKey}&with_genres=${selectedGenre}&total_pages=True`;
  const urlToFetch = `${tmdbBaseUrl}${discoverMovieEndpoint}${requestParams}`;
  try {
    const response = await fetch(urlToFetch);
    if (response.ok) {
      const jsonResponse = await response.json();
      const totalPages = jsonResponse.total_pages; 
      return totalPages;
    }
  }
  catch(error) {
     console.log(error);
  }
 }

and then i want to use it inside another function like that:

const getMovies = async () => {
  const selectedGenre = getSelectedGenre();
  const discoverMovieEndpoint = '/discover/movie';
  const requestParams = `?api_key=${tmdbKey}&with_genres=${selectedGenre}&page=${Math.ceil(Math.random()*getTotalPages())}`;
  const urlToFetch = `${tmdbBaseUrl}${discoverMovieEndpoint}${requestParams}`;
  try {
    const response = await fetch(urlToFetch);
    if (response.ok) {
      const jsonResponse = await response.json();
      const movies = jsonResponse.results; 
      return movies;
    }
  }
  catch(error) {
    console.log(error);
  }
};

so I can i display a random result from a random page, not just from the first page but I'm getting undefined. By the way, getSelectedGenre() works fine. I've searched here and in tmdb discourse page and found that others before me struggled with similar issue but couldn't find an answer.

chylinski
  • 85
  • 12
  • Have you tried to `await getTotalPages()` in `getMovies` ? – Robin Mackenzie Jul 30 '22 at 11:57
  • i have either by putting all the logic of `getTotalPages()` inside a nested `await fetch()` statement, or just now after your suggestion, assigning `await getTotalPages()` to a variable and using that variable in new `requestParams`. Same, undefined. – chylinski Jul 30 '22 at 12:16
  • Do you need to `await getSelectedGenre()` as well ? – Robin Mackenzie Jul 30 '22 at 12:30
  • no , it's a simple helper function that gets the value from a document element. The whole `getMovies()` listed above works fine (with `getSelectedGenre()` if i remove `&page` parameter from the request. It returns array of movies from the first page of movies of a particular genre. But there are multiple pages, i could access specific page, but i want to be able for my app to suggest a random movie from **all** pages, so i believe first i need to get a random page and then a random movie from a page. – chylinski Jul 30 '22 at 12:36

0 Answers0