"Exploring the usual progress of a standard GET request using Axios

My Objective:

I am utilizing Vue And Axios, with the goal of displaying the progress in percentage on the console.

The Challenge:

The request itself takes around 4 seconds or more because it fetches a large amount of data, processes it into an excel file, and then downloads it.

Approaches Tried:

I have explored two methods within Axios: onDownloadProgress and onUploadProgress.

The onDownloadProgress function works well but only triggers when the download initiates, not during the backend process of fetching data to generate an excel file (the most time-consuming task).

Here is the front-end implementation:

axios.get(`${env.ENDPOINT}reports/products/credits_export`, {
    params: {
      category_id: form_data.category_id
    },
    responseType: 'blob',
    onDownloadProgress: (progressEvent) => {
      let percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
      console.log(progressEvent.lengthComputable);
      console.log(percentCompleted);
    }
  }).then((res) => {
    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement('a');
    const file_name = `${new Date().toISOString().slice(0,10)}.xlsx`;
    link.href = url;
    link.setAttribute('download', file_name);
    document.body.appendChild(link);
    link.click();
    resolve(res.data);
  }).catch((e) => {
    reject(e);
  });

Plan Going Forward:

Splitting my progress tracking into two parts:

  • Download progress (using onDownloadProgress)
  • Request progress (preparing the Excel file for download)

Answer №1

It is difficult to predict the exact time it will take for the server to respond, making it challenging to display a progress bar at that specific moment. However, if dealing with streaming data, displaying progress is possible. To achieve this effect, you can simulate a progress bar by setting its state to show before making the call. Then, use a random percentage in a setInterval method to update the progress status until a response is received.

this.progress = true;
let interval = setInterval(() => {
this.progressPercentage = randomFunction()
 // perform calculations for progress
}, 500)
axios.get(url)
.then(() => {
   clearInterval(interval);
   // Utilize your progress event object 
})

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

Customizable form fields in AngularJS

Consider the scenario of the form below: First Name: string Last Name: string Married: checkbox % Display the following once the checkbox is selected % Partner First Name: Partner Last Name: [Submit] How can a form with optional fields be created in Angu ...

Loading screen featuring symbol percentage

https://i.sstatic.net/Ksogp.jpg How can I create a loading panel that includes a percentage symbol? I have searched for solutions but most of them suggest using a spinner. However, I specifically need a panel with the % symbol included. Is it possible to ...

What is the best approach to resolving the MongoServerError: E11000 duplicate key error?

Index.Js File: const cookieSession = require("cookie-session"); const express = require("express"); const app = express(); const helmet = require("helmet"); const morgan = require("morgan"); const dotenv = require(&q ...

Macy.js, a masonry library, experiences compatibility issues with Internet Explorer 11. However, the problem can be resolved by activating "inspect mode"

Having an issue with macy.js on my website. The masonry element doesn't work on IE11 initially, but when I toggle the "inspect element" feature on and off, it starts working suddenly. Is there a way to trigger it automatically right after the website ...

Maintaining the consistent structure of build directories within a Docker container is crucial, especially when compiling TypeScript code that excludes the test

Our application is built using TypeScript and the source code resides in the /src directory. We have tests located in the /tests directory. When we compile the code locally using TSC, the compiled files are deposited into /dist/src and /dist/test respectiv ...

Encountering a permission error when attempting to upload a file to the public folder on Vercel

Whenever I attempt to upload a file to the public folder on Vercel, I encounter the following error. ⨯ [Error: EROFS: read-only file system, open '/var/task/public/bb17ad93-017f-4fdf-a2db-713d9a390143.webp'] { errno: -30, code: 'EROFS& ...

Combining objects using ES6 import/export with async/await functionality

I am facing a situation where I have two files named config.js and config.json and my goal is to combine them into one object and then export it: config.json { "c": 3 } config.js import fs from "fs"; import fse from "fs-extra& ...

ng-grid automatically resizing columns based on content width

I am currently utilizing AngularJS ng-grid and endeavoring to accomplish the following tasks: 1. Adjust column width dynamically based on the content within each column. 2. Automatically resize the last column to fill the remaining space when hiding column ...

Every time I attempt to compile NodeJS, I encounter a compilation error

Within mymodule.js var fs = require('fs') var path = require('path') module.exports = function(dir, extension, callback){ fs.readdir(dir, function(error, files){ if(error) return callback(error) else { ...

Is it time for silverlight to take over for javascript once and for

It may seem like a far-fetched idea, but I can't help wondering if there is a way for Microsoft to come up with a new technology that allows C# code execution on both the server and browser side without relying on JavaScript. If all browsers were requ ...

Utilizing Angular.js to extract data from a deeply nested array of objects in JSON

Hello, I am currently learning about Angular.js and working on developing a shopping cart. In this project, I need to display an image, name, and cost of each product for multiple tenants. Each tenant has an array called listOfBinaries which contains listO ...

Guide to placing an icon next to a label with Vue Bootstrap

I'm working with a Vue Bootstrap input field setup like this: <b-form-group label="Name" label-for="name"> <validation-provider #default="{ errors }" name="Mapping Name" rules="required ...

Error: The property 'create' of undefined cannot be read (Material UI/enzyme)

When I mount a component, I encounter an error that does not occur when using shallow rendering. The specific error is: TypeError: Cannot read property 'create' of undefined at stylesOrCreator (node_modules/@material-ui/core/CircularProgress/C ...

Using the Ternary Operator in JavaScript to Dynamically Update HTML Elements with Angular

Is there a way to convert the code below into a ternary operator so that it can be used in an .HTML file? statusChange && statusChange === 'Employed' ? true : employmentStatus === 'Employed'; To clarify, I want to assign the re ...

Ways to avoid extra function loads in JavaScript

I'm currently working on an instant search feature and have some code implemented: $(function() { var timer; $("#searchterm").on('keypress',function() { timer && clearTimeout(timer); timer = setTimeout(doStuff, 800); tim ...

The user ID variable has not been declared

After successfully retrieving the username from a link, I am facing difficulty in getting the user id back. While displaying the username works perfectly fine, I encounter an issue with fetching the userId when trying to populate the thumbnail - it shows " ...

Tips for resetting the mapbox geocoder

Using the Mapbox Geocoder along with multiple select menus to customize a map has been my latest project. I am currently working on resetting the geocoder once a user selects an option from the menu, clearing the input field and removing the marker in the ...

VueJS throws an error when trying to access the 'settings' property of an undefined object

I'm encountering an issue with my basic input in a Vue component. The input should update data on change, but instead I'm getting the error message Uncaught TypeError: Cannot read property 'settings' of undefined Vue component <templ ...

assigning attributes to web addresses

Is there a way to set a style property for webpages by targeting addresses that contain /index.php/projecten/ instead of specifying each complete address in the code? Currently, I am using the following code: <ul class="subnavlist" style="display: &l ...

Guide to triggering a function upon selecting a row in a SyncFusion grid

My goal is to use a SyncFusion Vue Grid component and trigger a function when a row is selected. I attempted to include a column of edit buttons, but I am struggling to find the correct syntax to make these buttons call a function. Alternatively, I tried ...