It is possible to retrieve a variable from a secondary table within an API on a list page, but it is not possible to do

The functionality of this page, which reads and displays a full table from an API, is working flawlessly;

<template>
    <b-col>
        <h2>    
            Enrolments
            <b-button :to="{ name: 'createEnrolment', params: { id: this.$route.params}}" variant="warning" class="float-right">Create</b-button>
        </h2>

        <b-card
            v-for="enrolment in enrolments"
            :key="enrolment._id"
        >
            <p>Course id:{{ enrolment.course.id }}</p>
            <p>Course title:{{ enrolment.course.title }}</p>    
            <p>Status:{{ enrolment.status }}</p>
            <p>Created:{{ enrolment.created_at }}</p>
            <p>Date:{{ enrolment.date }}</p>
            <p>Lecturer:{{ enrolment.lecturer.name }}</p>
            <p>Lecturer email:{{ enrolment.lecturer.email }}</p>
            <p>Updated:{{ enrolment.updated_at }}</p>
            <p>Time:{{ enrolment.time }}</p>
            <b-button :to="{ name: 'viewEnrolment', params: { id: enrolment.id}}" variant="warning">View</b-button>
        </b-card>
    </b-col>
</template>

<script>
import axios from '@/config'

export default {
    name: "viewEnrolments",
    components: {},    
    data(){
        return {
            enrolments: []
        }
    },
    mounted() {
        this.getData()
    },
    methods: {
        getData() {
            let token = localStorage.getItem('token')

            axios
            .get(`/enrolments`, 
            {
                headers: {
                    "Accepted": `application/json`, 
                    "Authorization": `Bearer ${token}`
                }
            })          
            .then(response => {
                console.log(response.data)
                this.enrolments = response.data.data
            })
            .catch(error => console.log(error))
        }
    }
}
</script>

However, when attempting to view a single entry from the enrolments table, it encounters difficulty in accessing data from the courses table, resulting in the error: "TypeError: Cannot read properties of undefined (reading 'id')", which is stemming from line 8:

<p>Course id:{{ enrolment.course.id }}</p>

<template>
    <b-col>
        <h2>    
            Enrolments
        </h2>

        <b-card>
            <p>Course id:{{ enrolment.course.id }}</p>
            <p>Course title:{{ enrolment.course.title }}</p>    
            <p>Status:{{ enrolment.status }}</p>
            <p>Created:{{ enrolment.created_at }}</p>
            <p>Date:{{ enrolment.date }}</p>
            <p>Lecturer:{{ enrolment.lecturer.name }}</p>
            <p>Lecturer email:{{ enrolment.lecturer.email }}</p>
            <p>Updated:{{ enrolment.updated_at }}</p>
            <p>Time:{{ enrolment.time }}</p>
        </b-card>
    </b-col>
</template>

<script>
import axios from '@/config'

export default {
    name: "viewEnrolment",
    components: {},    
    data(){
        return {
            enrolment: []
        }
    },
    mounted() {
        this.getData()
    },
    methods: {
        getData() {
            let token = localStorage.getItem('token')
            
            axios
            .get(`/enrolments/${this.$route.params.id}`, 
            {
                headers: {
                    "Accepted": `application/json`, 
                    "Authorization": `Bearer ${token}`
                }
            })          
            .then(response => {
                console.log(response.data)
                this.enrolments = response.data.data
            })
            .catch(error => console.log(error))
        },
    }
}
</script>

Various attempts to link the courses table to the enrolment table have been made, all to no avail. The disparity in referencing the courses table between the two instances is perplexing to me.

Answer №1

It appears that there may be a small typo in the second component, specifically in the variable name viewEnrolment. The array is assigned to enrolments in the JavaScript:

  this.enrolments = response.data.data

However, in the component's HTML, the singular form enrollment is used:

<p>Course id:{{ enrolment.course.id }}</p>

Additionally, a tip for Vue components is to make API calls in the created() hook, rather than the mounted() hook. The created() hook is executed before the component is mounted to the DOM, ensuring that the data is available for use in the HTML template without any delays caused by API requests.

By following this approach, you can avoid situations where this.enrolment is accessed in the template before it has been fully fetched from the API.

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

What is the process for activating an event before another event on the same element with vanilla JavaScript?

Having an issue with the eventListener function. I am using the external library jquery.jstree-pre1.0fix2, which triggers a blur event on an input in my case. However, I need to trigger my event before the one from the library. I have come across some sol ...

What are the best methods for retrieving data from a subcollection in Firebase/Firestore with maximum efficiency

Utilizing Firestore to store posts with simple properties like {title: 'hi', comment: true} has been a seamless process for fetching user-specific data, given the structure of my collection: posts/user.id/post/post.name. An example would be posts ...

Manipulate Browser Navigation Behavior using JavaScript or AngularJS

How to Manage Browser Back Button Behavior Using AngularJS or JavaScript This is not a question, but rather a demonstration of how you can disable and manipulate the behavior of the browser's back button when using AngularJS or plain JavaScript. ...

Having trouble parsing asynchronous script with cheerio parser

Utilizing cheerio for web crawling poses a challenge when encountering websites with asynchronous scripts. When attempting to extract all the scripts from such websites, they are often missed in the process. Here is an example of the code I am currently us ...

Personalized AWS Cognito: Strategies for Tailoring Input Field Designs

MY CURRENT CHALLENGE: Within my Vue application, I am utilizing the AWS authenticator for managing login and signup processes. However, customizing its style has proven to be difficult due to the structure being built with shadow DOM elements. https://i. ...

Tips for creating a function that utilizes a select option value

I'm struggling with a form that includes two select inputs. I want the second input to only be enabled if the first one has been selected. I attempted using an onclick event, but it didn't work out as expected. Can anyone provide assistance? (apo ...

Having trouble transferring files to an unfamiliar directory using Node.js?

const { resolve } = require("path"); const prompt = require('prompt'); const fsPath = require('fs-path'); // Retrieve files from Directory const getFiles = dir => { const stack = [resolve(dir)]; const files = []; whi ...

Combining arrays using checkboxes in React.js

As someone completely new to coding, my current endeavor involves learning React by developing a flashcard app for studying Japanese. The concept revolves around incorporating a series of checkboxes that facilitate the selection of either Hiragana or Kat ...

Issue encountered when attempting to invoke a service from an Angular component within an office.js dialog

Our application utilizes Angular 5 and integrates Office.js to interact with Microsoft Office Word documents. Step 1: We use office displayDialogAsync to load the component. https://i.sstatic.net/uhT66.png Step 2: Inside the attribute-users component, an ...

The div remains unchanged when the button is clicked

My webpage is filled with several large div elements. There's a button on the page that, when clicked, should switch to the next div. Despite my efforts, the code I've written doesn't seem to be working as expected. :( This is the HTML st ...

Leveraging JavaScript and Thymeleaf to manipulate a list

I am trying to access an object from a list in JavaScript, which is being passed from the controller. Currently, I am working with Thymeleaf and Spring Boot. The list is named ${collaborateurs}. The following code snippet is functional: <script th: ...

Using Tailwind in a Vue component within a Nuxt application doesn't seem to be functioning properly

I am having trouble accessing a Tailwind CSS class within a component. Currently, I am using Tailwindcss with Nuxt.js. I can easily access the classes within the template, but the issue arises when trying to do so inside the <style> tag. <style ...

Error in Node.js (NPM Error)

Recently, I purchased a VPS running Ubuntu 14.4 and successfully installed Node.js 1.4. However, when attempting to run my script (node tradebot.js), I encountered the following error message! :-/ module.js:327 throw err; ^ Error: Cannot find ...

The file that is currently being downloaded has the .pptx extension, but it is being

Take a look at this code snippet: const generateDownload = ({ link, data, title, settings })=> { const newLink = document.createElement('a'); const blobUrl = link || URL.createObjectURL(new Blob([data], settings)); newLink.setAt ...

Create a personalized Command Line Interface for the installation of npm dependencies

I am looking to develop a Node CLI tool that can generate new projects utilizing Node, Typescript, Jest, Express, and TSLint. The goal is for this CLI to create a project folder, install dependencies, and execute the necessary commands such as npm i, tsc - ...

Canvas only draws outside the table, with the exception of the first one

I am facing an issue with placing multiple signature pads inside table cells. Only the first canvas gets drawn, while the others remain blank. I have checked the mouse/touch events. The events are triggered (up/down/move) and the draw function is called, ...

Utilizing Node.js to Retrieve Data from MySQL

Hi there, I'm new to NodeJS and I'm curious about how to fetch a MySQL query like we do in PHP. $query = mysql_query("SELECT * FROM accounts"); while($fetch = mysql_fetch_array($query)) { echo $fetch['Username']; } How would this be ...

There seems to be a glitch with the functionality of the HighStocks Tooltip

I've implemented a modified version of the example from highcharts: $(function () { $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) { // Create the chart $('#co ...

Don't delay in fulfilling and resolving a promise as soon as possible

Currently, I am facing an issue with a downstream API call that is returning a Promise object instead of resolving it immediately. This is how I am making the downstream call: const response = testClient.getSession(sessionId); When I console.log(response ...

Developing interactive checkboxes for individual rows through React.js

Within a form, I have rows containing two inputs each. Upon clicking "add", a new row is created. For the second row onwards, by clicking "add" a checkbox labeled 1 should be added to indicate dependency on the previous row. In addition, for the third row, ...