Tips on showcasing a collection of orders stored in a database using Vue.js

After successfully updating my orders post payment, I am wondering how I can showcase them on my Vue front end.

Below is the HTML template displaying the list of orders made:

<template>
  <div>
    <div
      v-for="order in orders"
      :key="order._id"
    >
      <div
        v-for="product in order.products"
        :key="product._id"
      >

        <a href="#">{{ product.productID.title }}</a>
      </div>
    </div>
  </div>
</template>

This is the script tag being used:


<script>
import { mapActions } from "vuex";
import { mapGetters } from "vuex";
import axios from "axios";

export default {
  name: "Products",
  data() {
    return {
      orders: [],
      name: "",
      email: ""
    };
  },
  created() {
    // User not authorized
    if (localStorage.getItem("token") === null) {
      this.$router.push("/login");
    }
  },

  mounted() {
    const token = localStorage.getItem("token");
    axios
      .get("http://localhost:5000/api/orders", {
        headers: {
          Authorization: "Bearer" + token,
          "x-access-token": token
        }
      })
      .then(res => {
        console.log(res);

        orders: res.products;
      });

    axios
      .get("http://localhost:5000/api/auth/user", {
        headers: {
          Authorization: "Bearer" + token,
          "x-access-token": token
        }
      })
      .then(res => {
        console.log(res);
        this.name = res.data.user.name;
        this.email = res.data.user.email;
      })
      .catch(error => {
        console.log(error);
      });
  }
};
</script>

Displayed below is the JSON object seen in the console:

[
    {
        "_id": "62d163b638cbafee24c6d663",
        "products": [
            {
                "productID": {
                    "_id": "625672a8370e769a8a93a51e",
                    "reviews": [],
                    "owner": {
                        "_id": "6220db7ee861f3dbbaf21e3d",
                        "name": "mr jacob",
                        "about": "hello",
                        "__v": 0
                    },
                    "category": "62566ec30e42d6c5ab370e7c",
                    "title": "galaxy note",
                    "description": "Lorem ipsum dolor sit amet, ",
                    "photo": "https://aji.s3.eu-west-2.amazonaws.com/1649832580792",
                    "price": 300,
                    "stockQuantity": 1,
                    "__v": 0,
                    "id": "625672a8370e769a8a93a51e"
                },
                "quantity": 1,
                "price": 300,
                "_id": "62d163b638cbafee24c6d664"
            }
        ],
        "owner": {
            "_id": "6278e8bc1966b7d3783ced8e",
            "name": "bas",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e7c7f6d5e79737f7772307d7173">[email protected]</a>",
            "password": "$2a$10$3QkbA805Pn/QBYMd6sULi.FGjETYoMf44wuV1mtOZahhPzm5zeL4G",
            "__v": 0,
            "address": "62b2cfd8d0846785cd87c64d"
        },
        "estimatedDelivery": "",
        "__v": 0
    }
]

I'm not receiving any errors in my console, so it's difficult to pinpoint the issue.

Answer №1

After reviewing your code, everything seems to be in order and it's functioning as expected. I did notice one minor detail though. According to the console data you provided, the correct syntax should be this.orders = res instead of orders = res.products.

Check out a live demo below:

new Vue({
  el: '#app',
  data: {
    orders: []
  },
  mounted() {
    const apiResponse = [
      {
        "_id": "62d163b638cbafee24c6d663",
        "products": [
          {
            "productID": {
              "_id": "625672a8370e769a8a93a51e",
              "reviews": [],
              "owner": {
                "_id": "6220db7ee861f3dbbaf21e3d",
                "name": "mr jacob",
                "about": "hello",
                "__v": 0
              },
              "category": "62566ec30e42d6c5ab370e7c",
              "title": "galaxy note",
              "description": "Lorem ipsum dolor sit amet, ",
              "photo": "https://aji.s3.eu-west-2.amazonaws.com/1649832580792",
              "price": 300,
              "stockQuantity": 1,
              "__v": 0,
              "id": "625672a8370e769a8a93a51e"
            },
            "quantity": 1,
            "price": 300,
            "_id": "62d163b638cbafee24c6d664"
          }
        ],
        "owner": {
          "_id": "6278e8bc1966b7d3783ced8e",
          "name": "bas",
          "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3a1a2b083a4aea2aaafeda0acae">[email protected]</a>",
          "password": "$2a$10$3QkbA805Pn/QBYMd6sULi.FGjETYoMf44wuV1mtOZahhPzm5zeL4G",
          "__v": 0,
          "address": "62b2cfd8d0846785cd87c64d"
        },
        "estimatedDelivery": "",
        "__v": 0
      }
    ];
    this.orders = apiResponse;
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div
       v-for="order in orders"
       :key="order._id"
       >
    <div
         v-for="product in order.products"
         :key="product._id"
         >
      <a href="#">{{ product.productID.title }}</a>
    </div>
  </div>
</div>

Answer №2

The issue was resolved by setting this.orders to res.data.products

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

Trying to figure out how to execute a codeigniter helper function with JQuery AJAX?

I created a handy function in my helper file within codeigniter that formats prices based on the value and currency ID provided. if(!function_exists('format_price')){ function format_price($val,$curency_id=NULL){ $CI ...

How to toggle a boolean variable in AngularJS when transitioning between states

Just getting started with AngularJS and trying to figure out how to tackle this issue. I have set up the following route: name: "Tracker", url: "/tracker/:period", and I have 3 distinct states for which I've created 3 separate functions to facilit ...

"Enhance your website with Express.js and eliminate the need for full

As I continue to work on my website, I am faced with a challenge. While the page is not overly large, I want to ensure that when navigating to different tabs in the navbar, the entire site does not have to reload each time. Currently, I am using express.js ...

"Android Webview's evaluateJavascript function is not returning the expected value

I am attempting to retrieve the username from a webview, but it is returning a null object. webView.settings.javaScriptEnabled = true webView.evaluateJavascript( "(function() { return document.getElementsByClassName('lgn-loginname') })() ...

Combining two arrays by finding common elements

Currently, I am working on a project where I retrieve data from the server, and each piece of data has to adhere to a specific format: const DATA = [ { title: {title: 'Main dishes'}, data: [ {_id: 1, type: 'Pizza'}, ...

NodeJS introduces the nullish coalescing assignment operator (??=) for effective nullish value handling

Is it possible to use the Nullish coalescing assignment operator (??=) in NodeJS? const setValue = (object, path, value) => { const indices = { first: 0, second: 1 }, keys = path.replace(new RegExp(Object.keys(indices).join('| ...

Implementing a JavaScript function that directs to the current page

I have set up my index page with a link that looks like this: <li onClick="CreateUser()"> <a href="#CreateUser">CreateUser</a> </li> When the "Create User" list item is clicked, the main page content is populated as follows: fun ...

Update a JSON value using an MUI Switch element

I am currently developing a feature that involves toggling the state of an MUI switch based on API responses. The status of the Switch is determined by the Active field in the API response. If the JSON field is 1, the switch is turned on, and if it's ...

Load the dropdown menu in the select element using the AngularJS $ngresource promise

I have a select box on my webpage that I need to fill with data received from a server. I am currently using a service to fetch this data, but I'm unsure how to access the values returned from the promise and populate the ng-options in the select tag. ...

Guidance on dividing children in an object into distinct arrays

So I have an interesting challenge while working on my project. I need help figuring out how to split a Javascript Object like the one below: { field1: { field2: { field3: "value 1", field4: "value 2" ...

Is it possible to utilize a JSON file to input events into FullCalendar that can accommodate multiple users?

Here's how I'm integrating event information from my database with FullCalendar using PHP: Retrieve event information from the database. Organize the data into an array and customize formatting, colors, etc. Convert the array to JSON format usi ...

JavaScript source control tool

Is there a Java-based version of GitHub? I am interested in developing a dynamic application using HTML5 and Javascript, and had the thought of integrating Git to monitor data changes. Therefore, I am curious if there exists a JavaScript adaptation of a G ...

Learn the method to conceal rows within a table simply by toggling a button

I need a function that will hide the rows below a row with a header and button, and only reveal them when another row with a header and button is clicked. When one of the +/- buttons is clicked, it should hide or expand all the rows with data content. http ...

Is it possible to make changes to local storage data without impacting the rest of the data set?

https://i.sstatic.net/BBcJF.pngI am looking for a way to modify specific data in the local storage without affecting any other stored information. However, I have encountered an issue where editing values works correctly for the first three attempts, but ...

Updating information without the need for a page refresh

My project involves text boxes and drop-down menus where users input data, then click "generate" to combine the text from the boxes and display the result on the page. I'm struggling with clearing these results if the user clicks generate again, for ...

What sets the Test Deployment and Actual Deployment apart from each other?

I have been developing a web application using Google App Script and I currently have multiple versions of the same web app with various fields. Interestingly, when I run one version through a test deployment, it displays correctly as expected based on th ...

Angular 4, Trouble: Unable to resolve parameters for StateObservable: (?)

I've been working on writing unit tests for one of my services but keep encountering an error: "Can't resolve all parameters for StateObservable: (?)". As a result, my test is failing. Can someone please help me identify and fix the issue? Here& ...

Utilizing the v-for loop to assign a class to an element

I am working with a v-for loop in my project, and I want to add a class that sets the background color to red when I click the action button for a specific line. Currently, when I click the button, it colors all indexes which is not the desired behavior. M ...

Loop variables undergoing change

I am currently working on a loop that fetches data from an API and then processes it to populate a simple array with the retrieved information. Promise.all(promises.map(obj => API.functionName(obj))).then((response) => { var index = startingDate; ...

Combining Context and MUI's theme provider for effective nesting: A step-by-step guide

Currently, I have a state set up to toggle between dark and light mode on a website that contains numerous nested components. The root App.js file looks like this: function App() { return ( <DarkModeProvider> ...