Retrieving data with VueJS using an axios promise

Can you help me figure out this issue?

Snippet :

<a href="#" class="video" @click.prevent="checkVideo(subItem.id)" :id="subItem.id" data-toggle="modal" data-target="#playerModal">{{subItem.name}}<span>{{getDuration(subItem.id)}}</span></a>

VueJS Function :

async getDuration(id) {
    var duration  = '';
    await axios.post('/api/v1/checkvideo', {
    menu: id
    })
    .then(function (response) {
    console.log(response.data[0].datas.duration)
    return response.data[0].datas.duration;
    });

    //console.log(duration);
    //return duration;
},

The question I have is that when using console.log the values appear as expected, but during Vue rendering, I am getting [object Promise]. How can I display the values after the promise has been resolved?

Your assistance would be greatly appreciated.

Answer №1

Your code is utilizing axios, which returns a promise object. If you wish to obtain the final duration, it is essential to await the axios promise and return the response accordingly.

async fetchVideoDuration(id) {
  let duration = '';
  const response = await axios.post('/api/v1/checkvideo', {
    menu: id
  });
  return response.data[0].datas.duration;
}

MODIFIED

As the async function inherently returns a promise, rendering [object Promise] may be observed on the screen. To accurately retrieve the duration for a specific identifier, following this approach seems appropriate.

data() {
  return {
    currentId: null,
    videoDuration: null
  };
},
mounted() {
  this.fetchVideoDuration(this.currentId);
},
methods: {
  async fetchVideoDuration(id) {
    let duration = '';
    const response = await axios.post('/api/v1/checkvideo', {
      menu: id
    });
    this.videoDuration = response.data[0].datas.duration;
  }
}

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

Attempting to use insertAdjacentHTML on a null property results in an error

I keep encountering the same error repeatedly... Can someone please explain what's going wrong here and provide a hint? Error script.js:20 Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null at renderHTML (script.js:20) a ...

Discovering unutilized node modules in your React project - A practical guide

Looking for a way to clean up unnecessary node modules and their dependencies from a project. I've done some research online and came across a few NPM packages that claim to achieve this, but none seem to meet my specific needs. Important: Node modu ...

Adjusting the size of images with precision after downloading from Google Cloud Storage

Struggling to resize an image after retrieving it from Google Cloud Storage. The streaming process is successful, but resizing seems to be an issue. The goal is to pass the image object to the sharpjs resize function, which will then resize the image and r ...

Tips for universally updating the FormData TypeScript interface within React Native applications

While attempting a simple append with FormData in React Native like the following... const formData = new FormData(); formData.append('image-data', { uri: '/awesome-chat-app/ImagePicker/abb9-a435046e971c.jpg', name: 'image001. ...

Conceal (and reveal) hyperlinks as the div's size changes dynamically

Is there a way to resize a div based on the user's decision to hide or show specific content? For example, take a contents page like this one (https://jsfiddle.net/4b1g5jp9/1/). When a user clicks 'hide', I want the div to adjust its size ac ...

What steps should I take when creating a web forum?

As a novice in web development, I am considering creating a simple web forum project. Can anyone offer guidance on how to get started or suggest a step-by-step approach? My current tech stack consists of vue2, express, mongodb with passport for authentic ...

Using Vue.js to create a table with dynamically colored rows in a v-for loop

I'm struggling to apply different colors to my table rows in a v-for loop. Currently, I'm developing a basic soccer app that displays recent match outcomes for a specific team. The issue I'm facing is related to changing the background c ...

Learn the art of altering Vuex store values dynamically

I have been exploring ways to utilize Vue.set() to dynamically modify bound data within Vuex store. After some trial and error, I came up with a solution that has been working for me. Please note that the code may not be the most elegant. This is my curre ...

Issue with Angular 5: Bootstrap Tooltip not functioning as expected

Where am I going wrong? I've been attempting to implement a Bootstrap Tooltip in Angular 5, but I'm facing some challenges. We have already set up the Javascript library through the footer of our index.html page as per the recommendations. The B ...

Vanilla JavaScript: toggling text visibility with pure JS

Recently, I started learning javascript and I am attempting to use vanilla javascript to show and hide text on click. However, I can't seem to figure out what is going wrong. Here is the code snippet I have: Below is the HTML code snippet: <p cla ...

The toast feature in Bootstrap 5 seems to be malfunctioning as it does not display properly despite the absence of any

Why isn't the Toast displaying in the code snippet below? I'm using bootstrap 5. I'm puzzled because there are no errors in the developer's tools. Any assistance would be greatly appreciated. <!DOCTYPE html> <html lang="en"& ...

Traverse through an array or object using recursive render functions in JavaScript

Here is an example of the issue I am currently trying to solve: https://codepen.io/wombsplitter/pen/KyWKod This is the structure of my array: [{ //obj 1 link: [{ //obj 2 link: [{ //obj 3 }] }] }] The ...

Automate Cart Updates with Increment and Decrement Buttons on the Cart Page of Magento 2 Store

On the cart page, I've added buttons to increase (+) and decrease (-) the quantity of a product. How can I make it so that the quantity updates automatically without needing to click on the update shopping cart button? Any suggestions on how to solve ...

Error: The unit tests encountered a SyntaxError due to an unexpected { token

I encountered the following error: D:\nginx\ibdrweb\webapps\ibdr-document-2\doc-app\sources\forms\dynamic-form\lus\lus.js:1 import { Tools } from "@ShareUtils/tools"; ^ SyntaxError: Unexpected toke ...

Extensive data entry command

I need to add around 12500 lines to my database for a game server map. This script helps me generate the query: sql = "INSERT INTO `legends`.`map` (`x`, `y`, `land`, `collision`, `impedance`, `effect`) VALUES " for (y=0;y<ig.game.collisionMap.data.leng ...

How can you use Jquery's .data() method to find elements with specific values?

I have a button that generates a new drop pin. The pin is contained within a div, and a hidden form input is also created to store the position of the pin when it's dragged. In my jQuery code for creating these elements, I assign a data attribute call ...

Extract data from ASP.NET session to JavaScript

I have been developing a web app using asp.net and angularjs. In order to pass my session variable from c# to javascript, I have implemented the following code: <script type="text/javascript"> var pm = "<%= Convert.ToString(Session["mysession ...

The variable remains undefined, despite the fact that the code executes correctly in a different location

I'm currently working on a multiplayer game in three js and integrating socket.io for real-time communication. I have all the player characters stored in an array called players on the server side. When each client connects, I send them the list of p ...

Tips for invoking a function using ng-model together with the ng-model value

Within a div element, I have a text field where I am using ng-model to capture the value. I need to trigger a function for validation when a date is entered in the text field. How can I achieve this while still utilizing ng-model? Any suggestions on how to ...

Store the selected checkbox values in an array when submitting in Ionic

One issue I am facing is that the checked checkboxes are returning true instead of the value of input (type="checkbox"). Array displaying responded checked or unchecked items I am unable to store this data in an array as needed. Additionally, I cannot sp ...