Categories
Development iOS

Map over Axios Response and append 2nd Axios Response to 1st

I’m creating a movie search React App using axios and the TMDb API. I want to make an axios.get call to search for a movie based on query, then map over the response, and pass the movie.id for each movie into a 2nd axios call to get more details for each movie.

I have tried many approaches, but I’m confused about how I need to return the values, or if I need to use async/await at some point in the code to wait for responses. I don’t really know the best way to go about this – there’s got to be a simple way to do it in sequence, but the asynchronous nature of the problem makes this difficult for me.

I thought it would be simpler to make my first axios call inside my search function, and then write a second function getDetails(id) that takes a movie id and makes an axios call with it.

Ideally, if I call the getDetails function in a map, get a response, append that response to my movies array, I could easily have an array of movies with appended details to each individual movie. I could then store the entire array in state, and use a single piece of state to manage all my movie data. I know that this process is not synchronous and that axios is promise based, but is there a way to go about this sequentially or am I approaching it all wrong? I know that .push() is not working in this situation, but I have tried other methods and they have always returned undefined, a promise, or an unintended result.

 const search = query => {
    axios
      .get(
        `https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&language=en-US&query=${query}&page=1&include_adult=false`
      )
      .then(response => {
        response.data.results.map(movie => {
          const details = getDetails(movie.id);
          return movie.push(details);
        });
      });
  };

  const getDetails = id => {
    axios
      .get(
        `https://api.themoviedb.org/3/movie/${id}?api_key=${API_KEY}&language=en-US`
      )
      .then(response => {
        return response.data;
      });
  };

Leave a Reply

Your email address will not be published. Required fields are marked *