What is the best way to merge two fetch requests in order to gather the required data?

If I want to create a website with details about movies, one crucial aspect is getting information on genres. However, there's a challenge in the main data request where genres are represented by IDs. I need to execute another query that includes these IDs and their corresponding genre names. Within a Vue component, I have set up a for loop to display essential information alongside genres. How can I merge these two queries effectively?

My Code:

movies.js

export default {
  actions: {
    async getPopularFilms({ commit }) {
      const res_movies = await fetch(
        'https://api.themoviedb.org/3/movie/popular?api_key=d502a3d84eb533756ec099ef127a2acd&language=en-US&page=1'
      );
      const { results } = await res_movies.json();
      commit('updateFilms', results);

      // Fetch genres
      const res_genres = await fetch(
        'https://api.themoviedb.org/3/genre/movie/list?api_key=d502a3d84eb533756ec099ef127a2acd&language=en-US'
      );
      const { genres } = await res_genres.json();

      let ids = [];
      let genres_ids = [];
      for (let id = 0; id < results.length; id++) {
        ids.push(results[id].genre_ids);
      }
      for (let id = 0; id < genres.length; id++) {
        genres_ids.push(genres[id]);
      }
      console.log(ids);
      console.log(genres_ids);
    },
  },
  mutations: {
    updateFilms(state, films) {
      state.popular = films;
    },
    updateGenres(state, genres) {
      state.genres = genres;
    },
  },
  state: {
    popular: [],
    genres: [],
  },
  getters: {
    returnFilms(state) {
      return state.popular;
    },
    returnGenres(state) {
      return state.genres;
    },
  },
};

PopularMovies.vue

<template>
  <div class="container mx-auto px-4 pt-8">
    <div class="popular-movies">
      <h2
        class="uppercase tracking-wider text-lg text-orange-500 font-semibold"
      >
        Popular movies
      </h2>
      <div
        class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4"
      >
        <div v-for="movies in returnFilms" :key="movies.id" class="mt-8">
          <img
            :src="'https://image.tmdb.org/t/p/w200' + movies.poster_path"
            alt="poster"
            class="hover:opacity-75 transition ease-in-out duration-150"
          />
          <div class="mt-2">
            <p class="text-lg mt-2 hover:text-gray-300">{{ movies.title }}</p>
            <div class="flex items-center mt1 text-sm text-gray-400">
              <svg class="fill-current text-orange-500 w-4" viewBox="0 0 24 24">
                <g data-name="Layer 2">
                  <path
                    d="M17.56 21a1 1 0 01-.46-.11L12 18.22l-5.1 2.67a1 1 0 01-1.45-1.06l1-5.63-4.12-4a1 1 0 01-.25-1 1 1 0 01.81-.68l5.7-.83 2.51-5.13a1 1 0 011.8 0l2.54 5.12 5.7.83a1 1 0 01.81.68 1 1 0 01-.25 1l-4.12 4 1 5.63a1 1 0 01-.4 1 1 1 0 01-.62.18z"
                    data-name="star"
                  ></path>
                </g>
              </svg>
              <span class="ml-1">{{ movies.vote_average * 10 }}%</span>
              <span class="mx-2">|</span>
              <span>{{ movies.release_date }}</span>
            </div>
            <div class="text-gray-300 text-sm">aaa</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';

export default {
  name: 'Popular Movies',
  computed: {
    ...mapGetters(['returnFilms']),
  },
  methods: {
    ...mapActions(['getPopularFilms']),
  },
  async mounted() {
    this.getPopularFilms();
  },
};
</script>

<style lang="scss">
.text-orange-500 {
  color: #ed8936;
}
</style>

Screenshots https://i.sstatic.net/yMMB4.png

https://i.sstatic.net/cFoch.png

My gets requests:

Answer №1

If you are looking to convert the genreIds to their corresponding names in the results, give this a try. Unfortunately, I am unable to test it at the moment as I am using a mobile device.

async fetchPopularMovies({ commit }) {
      const res_movies = await fetch(
        'https://api.themoviedb.org/3/movie/popular?api_key=d502a3d84eb533756ec099ef127a2acd&language=en-US&page=1'
      );
      const { results } = await res_movies.json();
      commit('updateFilms', results);

      // Retrieve genres
      const res_genres = await fetch(
        'https://api.themoviedb.org/3/genre/movie/list?api_key=d502a3d84eb533756ec099ef127a2acd&language=en-US'
      );
      const { genres } = await res_genres.json();

      const filmsWithGenres = results.map(({ genre_ids, ...rest }) => ({
        ...rest,
        genre_ids: genre_ids.map(id => genres.find(genre => genre.id === id).name )
      }));

      console.log(filmsWithGenres);
    },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

LESS: Using variable values in mixin and variable names

I am looking to simplify the process of generating icons from svg-files while also creating a png-sprite fallback for IE8 support. I am using grunt.js and less. I was inspired by the implementation on 2gis.ru: (in Russian), where they used technologies s ...

What is the best way for my web application to interface with a serial port?

I am working on a cloud-based web application that uses ASP Web API and Angular, both hosted on Azure. I have a requirement for my Angular app to communicate with a serial port for reading and writing data. How can I achieve this functionality? I've ...

Delve into the depths of Vue2's $emit command to gain a deeper comprehension

I'm curious about how Vue2's $emit function actually works. According to its API documentation(https://v2.vuejs.org/v2/api/#vm-emit), it states: Trigger an event on the current instance. Any additional arguments will be passed into the listene ...

Is it not possible to call a function directly from the controller in AngularJS?

I have been trying to update a clock time displayed in an h1 element. My approach was to update the time by calling a function using setInterval, but I faced difficulties in making the call. Eventually, I discovered that using the apply method provided a s ...

Tips for displaying a loading message during an AJAX request?

My AJAX function is set up like this: function update_session(val) { var session_id_to_change=document.getElementById('select_path').value; $.ajax({ type: "GET", url: "/modify_path/", asy ...

I am receiving a high volume of row data from the server. What is the best way to present this information on a redirected page?

There is a scenario where Page 1 receives a substantial amount of row data in JSON format from the server. The goal is to present this information on Page 2, which will be accessed by clicking on Page 1. To accomplish this task, JavaScript/jQuery and PHP ...

turn on labels for every individual cell in the bar graph

I'm working on setting labels of A, B, and C for each bar chart cell to display all my data on the chart. I attempted using data.addColumn('string', 'Alphabets'); but it's not functioning as expected. It seems like a simple ta ...

The identification number is not used to update Mongo DB

When attempting to use the MongoDB driver in Node.js to update a document, I encountered an issue where the log indicated that the update was successful, but the data did not reflect the changes. Specifically, despite trying to update the document using it ...

It is imperative that the query data is not undefined. Be certain to provide a value within your query function that is not undefined

I am utilizing a useQuery hook to send a request to a graphql endpoint in my react.js and next.js project. The purpose of this request is to display a list of projects on my website. Upon inspecting the network tab in the Chrome browser, the request appear ...

Combine the filter and orderBy components in AngularJS ng-options for a customized select dropdown menu

I am facing a challenge with my AngularJS dropdown that uses ng-options. I want to apply both the filter and orderBy components together in the ng-options section. The filter for the select is functioning correctly, but it seems like the OrderBy component ...

A unique Javascript feature that switches the text on various buttons

As someone who is relatively new to Javascript and web development, I am currently working on a project that involves creating multiple text areas for users to input and save text. Each text area is accompanied by a button with a unique ID that functions a ...

Is it possible to save an entire webpage that infinitely scrolls without actually manually scrolling through it?

I'm dealing with a webpage that has infinite downward scrolling. I tried automating the scrolling, but eventually the page became too large to continue scrolling. To fix this, I manually removed some DIV blocks from the source code which decreased the ...

Can AJAX function properly when the server-side code is hosted on a separate domain?

After opening Firefox's scratchpad and inputting the following code... function ajaxRequest() { var xmlhttp; var domainName = location.host; var url = 'http://leke.dyndns.org/cgi/dn2ipa/resolve-dns.py?domainName='; url = url + domainName + ...

The 'Cross domain jQuery Ajax request using JSONP' triggered an error: SyntaxError - Unexpected token : appeared on the screen

I've been struggling to extract information from the steam api, encountering persistent difficulties due to the error mentioned above. Below is the snippet of code I have been utilizing: var steamurl = "https://api.steampowered.com/IDOTA2Match_570/Ge ...

Managing Asynchronous Operations in Vuex

Attempting to utilize Vue's Async Actions for an API call is causing a delay in data retrieval. When the action is called, the method proceeds without waiting for the data to return, resulting in undefined values for this.lapNumber on the initial call ...

When incorporating MDX and rehype-highlight on a next.js site to display MD with code snippets, a crash occurs due to Object.hasOwn

I'm encountering an issue with my setup that is based on examples from next.js and next-mdx-remote. Everything was working fine until I added rehypeHighlight to the rehypePlugins array, which resulted in this error. Any thoughts on why this could be h ...

`json_encode does not output a UTF-8 character`

I send an AJAX request to the PHP server, and receive back an array encoded in JSON. This array has only two indexes. When I log it using console.log(), this is what I see: {"1":"\u00d9\u0081\u00db\u008c\u00d9\u0084\u0 ...

Sending data from jQuery to an AngularJS function is a common task that can be accomplished in

In my Controller, I have a function that saves the ID of an SVG path into an array when a specific part of the image.svg is clicked. $(document).ready(function(){ var arrayCuerpo=[]; $('.SaveBody').on("click", function() { ...

Issue with Angular UI-Router nested views: Content not displaying

I'm attempting to incorporate nested views for a webpage using angular ui-router. I have set up the state definitions according to various tutorials, but I am unable to display any content in the child views. Surprisingly, there are no errors showing ...

Issues with JQuery scroll() / scrollTop() functionality in Internet Explorer and Firefox

Our current script showcases a dotted line starting from the top of the screen leading to an up arrow. The position of the arrow changes based on how far the user has scrolled down the page, allowing them to click on the arrow and scroll back to the top. W ...