Having issues with async/await functionality within Vue 3's composable functions

Within my project, I implemented a function that handles file downloads. This function, onDownload, is triggered when the download button is clicked:

import {useOnDownload} from "../../use/useOnDownload"

setup() {

    ...

    const loading = ref(null)
    onDownload = async (id) => {
        loading.value = id
        await useOnDownload(id)
        loading.value = null
    }
    
    return {loading, onDownload}
}

To optimize code reusability, I centralized the API-related logic by creating a separate file named useOnDownload.js. This allows other components to utilize the same functionality.

export async function useOnDownload(id) {
    // make api call to server using axios
}

The issue I encountered is needing to properly handle the asynchronous nature of the useOnDownload function in order for the loader to function correctly.

Answer №1

Learn how to create asynchronous composable functions using the async/await syntax

export default function useOnDownload() {
  const isLoading = ref(true);

  const onDownload = async () => {
    isLoading.value = true;
    try {
      const { data } = await axios.post('/api/download', {id: id}, 
     {responseType: 'blob'})
        // handle the response

    } catch (error) {
      console.log(error);
    } finally {
      isLoading.value = false;
    }
  };
   // invoke the function
  onDownload();

  return { // place your reactive data here };
}


import useOnDownload from "../../use/useOnDownload"
// avoid using await in setup script or function 
const { reactiveDataReturned } = useOnDownload();

For more information, check out this article

Answer №2

For the await keyword to work within onDownload, it is necessary for it to be asynchronous

Answer №3

Your onDownlaod function includes the await keyword, even though it is not asynchronous. The following adjustment should be made to ensure proper functionality:

   // Ensure to include the following line
   onDownload = async(id) => {
    loading.value = id;
    await useOnDownload(id);
    loading.value = null;
}

Answer №4

I found an alternative solution without using async and await...

By passing the reference object loader as a function parameter (which is optional), I was able to manage it from there...

export function useOnDownload(id, loader) {
   if(loader !== undefined) {
     loader.value = id
   }
   axios.post('/api/download', {id: id}, {
      responseType: 'blob'
   }).then(response => {
     // handling the response
     ...
     if(loader !== undefined) {
       loader.value = null
     }
   }).catch(error => {
     // handling the error
     ...
     if(loader !== undefined) {
       loader.value = null
     }
   })
}

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

ways to run php script based on screen resolution or size

I have 2 php files that I need to execute based on screen size. include_once('large.php'); include_once('small.php'); The condition is to run large.php when the screen size is greater than 992px, and small.php when the screen size is ...

Navigating from production lines to the angular directive - what's the best route?

Can anyone advise on the proper method to initialize a variable with factory data in Angular? The current approach I'm using doesn't seem right to me. Am I doing it wrong? $scope.result = []; factoryCities.then(function(data){ $scope.result ...

Looking for a solution in Javascript and HTML to locate a main named window or tab and bring it to the front without loading a new URL into it

It is common knowledge that clicking <a href='a.html' target='abc'>...</a> will open a.html in a window named abc. However, if the window named abc already exists and I only want to bring it to the front without loading a.h ...

Having trouble retrieving coordinates from the ajax request and passing them to the Google Maps script

In my places.php file, I am retrieving coordinates from the database and confirming their accuracy through echoing. The connection to the database is established without any issues. A self-executing function has been created in order to continuously update ...

Unlike other templating engines, EJS does not automatically escape characters

In my current project, I am utilizing a Node JS server to query MongoDB and then display the results in an EJS template using the code snippet: res.render('graphFabric.ejs', {'iBeacons':[(beacon)]});. However, when attempting to re ...

The Springboot endpoint was successfully submitted through a fetch request, leading to a redirection to

Facing an issue while trying to submit a form to the /policy-holder page using fetch in JavaScript. The endpoint is redirecting to the login page, even though only admins are supposed to login. What could be causing this problem and how can it be resolved? ...

Display XML data from a service in a sleek panel using SAPIU5/Javascript

My payload contains XML content received from a service. I have an expand/collapse panel that, when clicked, should display the content of the payload in a label by binding it. However, the issue is that the content is not displayed in a prettyprint standa ...

Verify if a checkbox is selected upon loading the page

Hey there, I have a jQuery change function set up to turn an input text box grey and read-only when a user selects a checkbox. However, I'm interested in adding a check on page load to see if the checkbox is already selected. Any suggestions for enhan ...

Updating a route in Next.js? Make sure to remove the classList as you

Looking to remove a specific class whenever the route changes in Next.js, I've attempted the following approach: React.useEffect(() => { const activatedLink = router.query.tags const classActivated = document.querySelector('.'+activated ...

Tips for utilizing the .ready() function within the .load() method

With the implementation of a jQuery script on my website, I have created a dynamic platform where the main content changes as you navigate without fully reloading the page. However, there is an issue with the .load() function in jQuery that interferes with ...

Is Three.js deprecating the setHSL() function?

Searching for a solution to incorporate an HSL color scheme into my threejs project. The documentation seems to lack information on using .setHSL() or .offsetHSL() post-2013. Is there a preferred method to exclusively utilize HSL in a threejs scene? Appre ...

Guide to selectively hovering over a single object with raycasting

I'm encountering an issue with my code that handles object "hovering". The problem arises when multiple objects overlap and can be hovered over simultaneously if the meshes intersect at the mouse point. Although I know that the intersections array is ...

Code for jQuery is found in a separate file

Previously, all of my jQuery code was written in the main file. Now, I am attempting to move it to another js-file. However, I am encountering an issue where it is not working correctly. FireBug displays the following error: $ is not defined $(document).r ...

Vue JS encounters an HTTP 500 Internal Server Error when communicating with the

I have created an Asp.Net Core Web API and confirmed its functionality using Postman. After downloading the GitHub Project from this blog: , I updated the url in src/backend/vue-axios/axios.js to match my web api url. However, all I am getting is: HTTP500: ...

Monitor Changes with Grunt: Be Prepared for Some Waiting!

My Grunt watch task is experiencing significant delays between detecting a file change and starting to work. Output similar to the following is frequently seen: >> File "src/static/app/brandManager/addChannel.html" changed. Running "html2js:main" ...

Tips on transferring dynamically generated results to a user-friendly print window

After users complete a quiz, they receive their results. The client now wants to implement a "Print Results" feature that opens in a new window with customized CSS. I'm trying to figure out how to transfer the results to the new window using JavaScri ...

Rendering data in React using the array indexRendering data in React

I'm encountering an issue in React JS where I need to display all data from a REST API with a numeric index. REST API: [ { "id": "1", "start_date": "2020-05-08 09:45:00", "end_date": "2020-05-08 10:00:00", "full_name": "mirza", "cust_full_name": "fu ...

To avoid loading a CSS and JS file on a specific Rails controller, follow these steps:

Is there a way to prevent specific Rails app Controllers from loading the default css and js that is applied throughout the entire app? Appreciate you taking the time to read this. ...

Is a function repeatedly invoked?

I have implemented a Pagination component in NextJS as follows: import Pagination from 'react-bootstrap/Pagination'; import Router from "next/router"; import {useEffect} from "react"; export { Paging } function Paging(props) ...

We have successfully implemented version x3 validation using Netlify forms

Currently, I have a functional form that submits using Netlify forms, making the process straightforward by simply adding name="contact" data-netlify="true" method="POST". This setup handles all the backend work seamlessly. The basic structure of my form ...