What are the steps to troubleshoot a Vue application?

I've encountered an issue with a code snippet that retrieves JSON data from a RESTful API. The code only displays the .container element and reports that the items array is empty, even though no errors are being shown. I attempted to debug the problem by using console.log to display the fetch result, so I inserted

let result = await fetch('video').then(res => res.json())
into the code. However, nothing appeared in the browser console, indicating that the async getData function may not be running. I'm puzzled by this behaviour and unsure of what could be causing it.

<template lang="pug">
.container
  .columns(v-for="n in lines")
    .column.is-3.vid(v-for='item in items')
      .panel
        p.is-marginless
         a(:href='item.videoId')
           img(:src='item.thumbnail')
        .panel.vidInfo
          .columns.hax-text-centered
            .column
              .panel-item.reddit-ups
                span {{ item.score }}
                i.fa.fa-reddit-alien.fa-2x
              .panel-item.reddit-date
                i.fa.fa-calendar.fa-2x
</template>
<script>
export default {
      name: 'main',

      data: () => ({
        items: [],
        lines: 0
      }),

      async getVideo () {
        this.items = await fetch('/video').then(res => res.json())    
        this.lines = Math.ceil(this.items.length/4)

      }
  }
  </script>

Answer №1

Your code has a few issues that the console should warn you about.

Start by defining the data object as an ES6 Object Method Shorthand instead of using arrow functions:

data() {
  return {
    items: [],
    lines: 0
  }
}

Next, if 'getVideo' is a method, it should be placed under the methods object:

methods: {
  async getVideo () {
        this.items = await fetch('/video').then(res => res.json())    
        this.lines = Math.ceil(this.items.length/4)
  }
}

I recommend using the created hook to trigger this method, but you can choose when to trigger it (on click, instance creation, or mounting):

<script>
export default {
      name: 'main',

      data() {
        return {
          items: [],
          lines: 0
        }
      },

      methods: {
        async getVideo () {
           await fetch('/video')
              .then(res => res.json())
              .then(items => this.items = items)    
           this.lines = Math.ceil(this.items.length/4)
        }
      },

      created() {
        this.getVideo()
      }
  }
  </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

What could be causing the absence of the ID definition?

Whenever I send a DELETE request, I receive an error message stating ReferenceError: id is not defined at Object.removeOne (...\services\user.js:16:38. I am unsure about the role of 'id' in \services\user.js and why it is not ...

Possible revision: "Exploring ways to iterate through an array of objects in Node/Express and verify if a corresponding entry exists in a MongoDB

Working on building a web application using the MEAN stack and Yelp API to retrieve an array of objects representing local businesses. I manipulate this data on the front-end, but before sending a response, I need to verify if a specific object exists in m ...

Show a property from the local storage as an option in ng-options

Within my Angular application, I keep crucial victim data in local storage. This data is then showcased in the view where it can be altered (via a <select>): <h1>Victim #{{victim.numero}}</h1> <label>Victim status</label> &l ...

Exploring Three.js: Meshes, Triangles, and the Beauty of Lambert

I have a function that generates stars, here is the code: function CreateStar( radius, thickness, isWireframe, starColor) { // material var starMaterial = new THREE.MeshLambertMaterial({ color: starColor, ...

Have you ever encountered the frustration of being unable to navigate to the next page even after successfully logging in due to issues

I'm currently utilizing Vue and Firebase to build my application. One of the features I want to implement is the redirect method using vue-router. Within my vue-router code, I've included meta: { requiresAuth: true } in multiple pages as middlew ...

The Ajax response is not providing the expected HTML object in jQuery

When converting HTML data from a partial view to $(data), it's not returning the jQuery object I expected: console.log($(data)) -> [#document] Instead, it returns this: console.log($(data)) -> [#text, <meta charset=​"utf-8">​, #text ...

Leverage Vue Router with scripting

I've come across a script that automatically redirects users to the login screen if they receive response code 401 from an API, indicating that their session has expired. import axios from 'axios'; axios.interceptors.response.use(function ...

Vue.js displaying the error message: "The maximum size of the call stack has been exceeded"

Could you assist me in resolving this issue? router.js routes: [{ path: "", component: () => import("@/layouts/full-page/FullPage.vue"), children: [{ path: "/pages/login", name: "page-login", component: () => import("@/views/pages ...

The functionality of the Angular directive ngIf is not meeting the desired outcome

We are currently working on transferring data from one component to another using the approach outlined below. We want to display an error message when there is no data available. <div *ngIf="showGlobalError"> <h6>The reporting project d ...

What could be causing the failure in revealing these elements?

Within my Meteor application, I utilize Template.dynamic to seamlessly replace the current Template with the next one. In my "main" html file, the setup looks like this: <div class="container"> {{> postTravelWizard}} </div> </body> ...

Guide to seamlessly navigating to an element using a hash in NuxtJS

My aim is to create a smooth scrolling anchor link menu using Nuxt.js, where the user can click on a link and be directed to the corresponding page section. However, I'm facing a dilemma as there are multiple approaches to achieve this functionality, ...

The fetch() POST request is met with an error message stating "415 Unsupported Media Type"

I keep encountering a 415 error when attempting to upload a PDF file using fetch(). The PDF file resides in the same directory as the js file, and the name is correct. async function uploadFile(filePath, extension, timestamp) { const url = "https ...

Unable to establish a hyperlink to specific section of page using MUI 5 Drawer

When attempting to link to a specific part of my first page upon clicking the Shop button in the navigation Drawer, nothing happens: https://i.stack.imgur.com/FUQCp.png This snippet shows the code for the MUI 5 Drawer component: <Drawer anch ...

The powerful combination of knockout.js, breeze, and dynatree/fancytree offers a dynamic and

This concept is really challenging for me to grasp as I am not accustomed to this particular style of programming or data management. Presently, my main objective is to pass a JSON object retrieved through Breeze into a Dynatree or Fancytree. All the ava ...

Are there any methods to alter the current preFilters within jQuery?

Is there a way to access and manipulate the internal jQuery preFilters using the jQuery.ajaxPrefilter() function? In version 1.11.1, I noticed a private preFilters object declared on line 8568, but it doesn't seem like there is a built-in method to in ...

Is the removal of the Vue-Router link happening when you click on the top app bar icon in Google Material

Review of the following code snippet: <!DOCTYPE html> <html> <head> <title>test</title> <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='vie ...

The component is unable to access VueJS references

Below is a simplified version of the code I am working with: <html> <head> <script src="file:///D:/OtherWork/javascript/vue/vue.js"></script> </head> <body> <div id="app"> & ...

What is the process for storing form data into a text file?

Despite seeing similar questions in the past, I am determined to get to the bottom of why this code isn't functioning as expected. My goal is to input form data into a .txt file using a post request. While I lack extensive knowledge of PHP, I am pieci ...

Is it possible to make nested HTML list items align to the left?

Is it possible to align nested HTML list items to the left? For example: Bat Cat Ratonetwothree Mat <ul> <li>Bat</li> <li>Cat</li> <li>Rat<ul><li>one</li><li>two< ...

React Error boundary is failing to perform as anticipated

Having issues implementing an error boundary in React. Here is the code snippet: ErrorBoundary.js import React from 'react'; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: fal ...