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

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

Unpredictable preset inline styles for HTML input elements

While developing a full-stack MERN application, I encountered an unusual issue when inspecting my React UI in Chrome DevTools. If any of these dependencies are playing a role, below are the ones installed that might be contributing to this problem: Tail ...

I am interested in utilizing $axios in conjunction with Vuex constants for my project

My Dream Becoming Reality I frequently use this.$axios, so I attempted to store it in a constant, but unfortunately, it did not work as expected. Despite reading the official documentation, I couldn't grasp the reason behind this issue. Could it be d ...

Assigning a variable within a parent function from a child function in JavaScript

Struggling to assign the value of "result" in the inner function. Any suggestions on how to do this? I am able to console log the result variable inside the function, but a friend recommended using promises. However, I have no clue how to implement that ...

Ensure that the <TabPanel> content occupies the entire width and height of its parent container

Currently, I am working with React and material-ui. Specifically, I am utilizing an appbar with tabs and my goal is to have the content of each tab expand to full width and height when selected. If you'd like to see an example, check out this sandbox ...

Using ajax to submit variables may not function properly

I have a set of data that has been processed using JavaScript and I am looking to save it to a database. I have been attempting to code something with AJAX, but so far, I have had no success... What I require: Two variables (id, name) need to be sent to a ...

Exploring unit tests: Customizing an NGRX selector generated by entityAdapter.getSelectors()

Let's imagine a scenario where our application includes a books page. We are utilizing the following technologies: Angular, NGRX, jest. To provide some context, here are a few lines of code: The interfaces for the state of the books page: export int ...

Check for the presence of an Outlook add-in within a web application

I'm having trouble determining whether my hosted web application is being accessed through a browser or from within the Outlook 2013/2016 client. I have developed a web application that offers different functionalities depending on whether it is acce ...

Creating a circle in SVG that cannot be scaled using Javascript

I'm working on a map project using JavaScript and SVG for drawing the lines. One feature I'd like to implement is the ability to search for a specific road, and if found, display a circle on the map. I understand how to draw a circle in SVG, bu ...

Enabling the execution of returned scripts using JQuery AJAX

I have a hyperlink that I need to send a DELETE request using JQuery through AJAX. if(confirm("Do you wish to proceed?")) { $.ajax({ url: $(this).attr("href"), type: 'DELETE', success: function(result) { // Perform act ...

Incorporating code execution during promise completion

I'm currently working on an express application that involves a generator function which takes approximately 5 minutes to process a large amount of data. Unfortunately, I am unable to optimize this function any further. Express has a built-in ti ...

The Cascading of Bootstrap Card Designs

Looking for some assistance with my TV Show Searcher project that is based on an API. The functionality is complete, but I'm struggling to get the Bootstrap cards to stack neatly without any empty space between them. I want it to resemble the image ga ...

Message from Discord: Unable to access the property 'MessageEmbed' because it is undefined

Attempting to create a simple welcome message embed. Here is my main.js file without the login token: const Discord = require('discord.js'); const client = new Discord.Client(); const MessageEmbed = new Discord.MessageEmbed(); const prefix = &ap ...

What is the significance of the -infinity value in the JavaScript console?

Recently, while learning JavaScript ES6, I came across a strange result of -infinity on my console when running the following code: let numeros = [1, 5, 10, 20, 100, 234]; let max = Math.max.apply(numeros); console.log(max); What does this ...

Using default language in Next.js internationalization: a step-by-step guide

I've been immersing myself in the Nextjs internationalization documentation for the past two days. My goal is to have support for two languages: en, fa. I also want to be able to switch between them with URLs structured like this: https://example.com ...

Edge Browser does not support PHP Websocket technology

I created a multiplayer card game and incorporated a websocket for functionality. To integrate the websocket in php, I utilized this specific library After deploying it on my Ubuntu server, the program functioned smoothly on Chrome and Firefox (The fronte ...

What could be the reason for the esm loader not recognizing my import?

Running a small express server and encountering an issue in my bin/www.ts where I import my app.ts file like so: import app from '../app'; After building the project into JavaScript using: tsc --project ./ and running it with nodemon ./build/bin ...

Idea: Develop a bookmarklet that generates a header form and deletes it upon submission

After much contemplation and experimentation, I have been grappling with the idea of creating a bookmarklet that displays a header when clicked on any webpage. This header will contain a small form that submits its contents to a server before disappearing. ...

Displaying XML data in an HTML table

Encountered a challenge while fetching data from an external XML document using JS. Following the w3schools tutorial for AJAX XML, but faced an issue I couldn't resolve. The XML structure is as follows: <root> <document-id> <author ...

Tips for iterating through the properties of every object within a Knockout observableArray and dynamically generating a table

My observableArray is dynamically populated with SQL data, resulting in varying columns each time. I am trying to present the SQL results in an HTML table but facing issues with the code below. This is the desired output format... var viewModel = func ...

Refreshing a PNG file without the need to refresh the entire page

Developed a captcha using imagestring imagestring($image, 5, 5, 30, $text, $text_color); imagepng($image,"captcha_image.png"); imagepng($image,"captcha_image.png"); The code snippet above shows part of the implementation. <img ...