How can we efficiently trigger a function that sends an axios request by leveraging data from a v-for loop?

Currently, I am developing an e-commerce platform using Rails and VueJS. In order to display the orders of a specific user, I have created a component file. Within this component, I am utilizing a v-for loop to iterate over and showcase all the information related to the user's orders. Each order is associated with a carted products table where the product ID is stored. My objective is to exhibit the product details of each product within every order. To achieve this, I have implemented a productShow function that triggers an axios request to fetch the product information from the backend. However, my challenge lies in capturing the product ID from each product in the carted product array to include in the request. Moreover, I am unsure about how to display each product within its corresponding order along with the order details. Despite numerous attempts, I have not been successful so far and am seeking guidance. Below, you can find both the code and relevant information.

The component for ordersIndex.vue:

<div class="home">
    <h1>{{ message }}</h1>
    <div  v-for="order in orders">
      <h2>Order Number:{{ order.id }}</h2>
      <h1 v-for="cartedProduct in order.carted_products"> <strong>{{ cartedProduct }}</strong> </h1>

      <h3>SUBTOTAL:{{ order.subtotal }}</h3>
      <h3>TAX:{{ order.tax }}</h3>
      <h3>TOTAL: {{ order.total }}</h3>

    </div>
  </div>
</template>

<style>
</style>

<script>
import axios from "axios";

export default {
  data: function () {
    return {
      message: "Your Orders",
      orders: [],
      anOrder: [],
      cartedProducts: [],
      product: {},
      productId: "",
    };
  },
  created: function () {
    console.log("In Created...");
    this.orderIndex();
  },

  methods: {
    orderIndex: function () {
      console.log("In orderIndex...");
      axios.get("/api/orders").then((response) => {
        console.log(response.data);
        this.orders = response.data;
        this.cartedProductsonOrder();
      });
    },
    productShow: function (id) {
      console.log("in products show");
      axios.get("/api/products/" + id).then((response) => {
        console.log(response.data);
        this.product = response.data;
        console.log("Line 53");
        console.log(this.product);
        this.cartedProducts.push(this.product);
        console.log(this.cartedProducts);
      });
    },
    cartedProductsonOrder: function () {
      console.log("In cartedProductsonOrder method....");
      console.log(this.orders);
      for (let i = 0; i < this.orders.length; i++) {
        console.log("Line 62");
        console.log(this.orders[i].carted_products);
        this.cartedProducts = this.orders[i].carted_products;

        for (let j = 0; j < this.cartedProducts.length; j++) {
          console.log("Line 67");
          console.log(this.cartedProducts[j]);
          console.log(this.cartedProducts[j].product_id);
          this.productId = this.cartedProducts[j].product_id;
          this.productShow(this.productId);
        }
      }
    },
  },
};
</script>

Here are screenshots of the console log for reference:

order response

carted products

Answer №1

This code snippet is untested, but it should help you understand how to achieve your goal. Some improvements have been made, such as using arrow functions and replacing basic for loops with forEach loops.

<template>
  <div class="home">
    <h1>{{ message }}</h1>
    <div v-for="order in orders">
      <h2>Order Number:{{ order.id }}</h2>

      <h1 v-for="product in order.carted_products"> <strong>{{ cartedProduct }}</strong> </h1>

      <h3>SUBTOTAL:{{ order.subtotal }}</h3>
      <h3>TAX:{{ order.tax }}</h3>
      <h3>TOTAL: {{ order.total }}</h3>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data: () => ({
    message: "Your Orders",
    orders: [],
    cartedProducts: []
  }),
  mounted() {
    this.doGetOrders();
  },
  methods: {
    doGetOrders() {
      axios.get(`/api/order`).then((response) => {
        this.orders = response.data;

        this.doCartedProductsInOrder();
      });
    },
    doCartedProductsInOrder() {
      if (this.order.length >= 1) {
        this.order.forEach((order) => {
          if (order.cartedProducts >= 1) {
            order.cartedProducts.forEach((productId) => {
              this.cartedProducts.push(this.doGetProductInfo(productId));
            });
          }
        });
      }
    },
    doGetProductInfo(productId) {
      axios.get(`/api/products/${productId}`).then((response) => {
        if (response.status === 200) {
          return response.data;
        }
      });
    }
  }
}
</script>

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

Pulling JavaScript - referencing an external script

I am currently facing a challenging dilemma that requires a simple yet intricate solution. My objective is to develop a script capable of playing chess on my behalf, utilizing an engine to determine the optimal moves for pieces such as rooks, bishops, king ...

Hold up in paths with identical modules

Utilizing vue router for navigating with transitions and vuex to fetch and store data from a JSON API has been successful. The issue arises on routes that utilize the same component. After a route change, there is a momentary display of the old state of t ...

"Effortlessly move elements with HTML5 drag and drop functionality from either direction

I'm working on an application that requires Html5 Drag and Drop functionality, which is currently functioning well. However, in the app, there may be instances where a dropped item is no longer needed and I want to allow users to re-drag and drop it b ...

Generate a random number to select a song file in Javascript: (Math.floor(Math.random() * songs) + 1) + '.mp3'

My current JavaScript code selects a random song from the assets/music folder and plays it: audio.src = path + 'assets/music/'+(Math.floor(Math.random() * songs) + 1)+'.mp3' However, I've noticed that sometimes the same trac ...

Launching a new tab with a specific URL using React

I'm attempting to create a function that opens a new tab with the URL stored in item.url. The issue is, the item.url property is provided by the client, not by me. Therefore, I can't guarantee whether it begins with https:// or http://. For insta ...

Tips for making an ajax call in Angular 6

As a backend developer, I have limited experience with Angular. How can I send an ajax request from Angular to test my API? The request needs to be sent before clearing the localeStorage. Can you provide guidance on how to achieve this? <button (clic ...

Executing the beforeRouteLeave navigation guard on a vue component for testing purposes

I am facing a challenge with unit testing the routing behavior of a vue component using jest. Specifically, when navigating away from the component, the 'beforeRouteLeave' guard in Vue-router is not triggering during testing, even though it works ...

Transforming arrays into nested objects using JavaScript

My array consists of objects structured like this: var exampleArray = [{ name: 'name1', subname: 'subname1', symbolname: 'symbol1' }, { name: 'name1', subname: 'subname11', symbolname: 'sy ...

How to retrieve the value of a table row by clicking with the mouse using jQuery?

I am having an issue with my table data display. Each row in the table is assigned a unique ID, which corresponds to the value of the tr-tag. My goal is to log this ID in the console when a table row is clicked. Here is the table: $.getJSON(`http://local ...

Integrate the perfect-scrollbar jQuery plugin into RequireJS

Recently, I decided to explore RequireJS for my projects but I am still trying to understand its functionalities. I'm currently attempting to incorporate perfect-scrollbar, specifically the jQuery version, into my work. Here's a snippet from my ...

Trouble with Vue 3 watch not persisting after page refresh

Attempting to create a Vue application that supports two languages, utilizing local storage and store to store the selected language. Initially, everything appears to be functioning correctly. After the user logs in, the default language is displayed in b ...

Experiencing troubles when trying to execute npm run serve with vue/cli

I started a project with the following commands: vue create test After navigating to my repository: cd test When I tried to launch it using: npm run serve I encountered an issue: INFO Starting development server... ERROR Error: No valid exports m ...

Modifying the values of Highcharts-Vue chart options does not result in any changes once they have been

I recently started incorporating Highcharts into my Vue project using the highcharts-vue library. A) Initially, in pure JavaScript, the following code snippet functions as expected: let b = 5; let data = { a: b } console.log('data', data.a) ...

Managing logout feature effectively in Vue.js/LaravelEnsuring proper logout functionality

I'm currently in the process of building a simple SPA with Vue and Laravel. So far, I've managed to set up user registration and login functionalities. However, one thing that's stumping me is how to implement a logout feature. Here's ...

Improve Email Regular Expression to Restrict Consecutive Periods

I'm not very good with regular expressions, so I decided to seek some help. Here's the regular expression I have: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.) ...

What is the best way to generate an error message in AJAX?

It seems that I am facing an issue with throwing an error message to indicate whether an email exists in my user table. I have realized that due to the asynchronous nature of AJAX, try and catch error messages cannot be used within the complete function. E ...

When using Selenium WebDriver, the WebElement .findElement method can sometimes cause errors in JavaScript

Successfully locating the element, I am able to retrieve the text within the container. However, when attempting to fetch the titles of products by iterating through the array of WebElements inside the container, the .findElement() consistently throws an e ...

How can we maintain line breaks in Textfields when using React-Admin and Material UI?

Currently, I am working with React-Admin and encountered an issue where my database field contains line breaks (\n). However, when I try to display it on a page using the following code: <TextField source="extra_details" /> The line breaks are ...

Node JS fails to return body content in POST request

Exploring Node JS for the first time and attempting to post data to a specific URL and retrieve it. Using Postman for this task, but encountering an issue where the response data is coming back as undefined despite receiving a 200 status code. Even after ...

JWPlayer encounters an issue: "undefined" function is not defined

Can anyone lend a hand with this issue I'm facing? I'm attempting to upload a video using jwplayer but encountering errors. Here is the snippet of code I'm utilizing: <script type="text/javascript"> jwplayer("leg ...