"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

The REST API request returns a response code of 0

I have been attempting to make an API call to the Insightly API using this code: var x = new XMLHttpRequest(); x.open("GET", "https://api.insight.ly/v2.2/Projects/Search?status=in%20progress&brief=false&count_total=false", true); x.setRequestHeade ...

Toggle divs by using a checkbox (Vue.js)

On my authentication page, I have implemented a checkbox that I want to use to toggle between Sign Up and Sign In forms. When the checkbox is clicked, it should display the Sign Up form, and when it's unchecked, it should show the Sign In form. I fou ...

Strange occurrences observed while looping through an enum in TypeScript

Just now, I came across this issue while attempting to loop through an enum. Imagine you have the following: enum Gender { Male = 1, Female = 2 } If you write: for (let gender in Gender) { console.log(gender) } You will notice that it iter ...

Troubleshooting a mysterious anomaly with a jQuery UI button

Would like to achieve something similar to this: http://jqueryui.com/demos/button/#icons When trying to replicate it, http://jsfiddle.net/p5PzU/1/ Why is the height so small? I expected a square shape but am getting a rectangle instead. What could be c ...

"The Material UI date picker is encountering an issue with the error prop, which is being evaluated

I have developed a date picker that utilizes the Jalali calendar. While attempting to pass error checking using the error prop in the following code: <LocalizationProvider dateAdapter={AdapterJalali}> <MobileDatePicker label={lab ...

My form submission is getting messed up by VueJS, causing it to delete all of the data

It seems that VueJS is causing issues with my form submission process, as it is removing the post data from the Ajax serialize() function. I suspect it could be due to the combination of using Ajax and Jquery, but I'm unsure how to resolve this issue ...

The Vue directive v-for with an empty key attribute does not function properly

Looking for some assistance. In my App.vue file, I have the following code: <template> ... <select class="form-control"> <option v-for="{car, index} in cars" :key="index"> {{ car.name }} </option> </select> ...

Disconnect occurred during execution of Node.js "hello world" on a Windows 7 operating system

Issue Resolved: Oh no! jimw gets 10000 points for the solution! I've decided to delve into a hobby project using Node.js. Here's where I started: Downloaded and installed Node version 0.6.14 Copied and pasted the classic "hello world" program ...

Collaborating on data through module federation

Currently, I am in the process of developing a Vue.js and TypeScript application using Vite. In addition, I am utilizing the vite-module-federation-plugin for sharing code across different applications. My main inquiry revolves around whether it is possibl ...

How can non-numeric characters be eliminated while allowing points, commas, and the dollar sign?

Looking for an efficient method to filter out all characters except numbers, '$', '.', and ','. Any suggestions on achieving this task? ...

Harness the power of electrons with the simple push of a button - initiating program execution

Recently, I delved into Electron with the desire to create a small application for myself. This app would allow me to run different programs or games by simply clicking on a link. My goal is to have the program/game start automatically when I open the Ele ...

Encountering an unrecoverable SyntaxError while trying to deploy a website on Netlify

When using commands like npm start, npm run build, and pm2 start server.js, everything runs smoothly without any errors. However, I encounter an issue when trying to deploy my project on Netlify. The Chrome console displays the error: Uncaught SyntaxError: ...

Contrasts between the storage of data in a static function versus a static object

Trying to figure out the best way to reset a react class component back to its initial state, I came across two different implementations. In my own version, I created an object with initial values and set the component's state equal to it: // My imp ...

Problem with Ionic App crashing

Currently, I am developing an Ionic app that relies on local storage for offline data storage. The app consists of approximately 30 different templates and can accommodate any number of users. Local storage is primarily used to store three key pieces of i ...

The function history.popstate seems to be malfunctioning, as it is triggered by both the forward and backward navigation buttons in

When I press the back button, I am attempting to retrieve the previous state. Upon inspecting, I noticed that the popstate function is also triggered by the forward button. However, it does not revert to the previous state even though the popstate function ...

Utilizing jQuery and CSS to make an entire div clickable, and activate an 'a' tag hover state upon hovering

Looking to create a clickable link for the .wrapper div that directs users to the location of a.icon. Want the .wrapper div to activate the a.icon:hover state when hovered over, not just when hovering over the icon itself. Any assistance would be highly a ...

Using anti-cache code in jQuery's getJson function

During an interview, I was presented with the following question: Can you provide a one-liner code showing the proper syntax to add an anti-cache code to all jQuery getJson calls in a project without individually adding it to each call? I must admit th ...

Tips for determining whether a value is present in an array or not

I'm trying to prevent duplicate values from being pushed into the selectedOwners array. In the code snippet below, the user selects an owner, and if that owner already exists in the selectedOwners array, I do not want to push it again. How can I imple ...

What is the best way to achieve varying margins when adding divs in CSS?

Encountering CSS margin issues when adding new divs. Desiring a large margin between the Create Div button and minimal margin between Example Text Here. The desired outcome Margin is too small between Create Div button and Example Text Here, but good bet ...

Modifying the nested data organization in Sequelize

I'm looking to adjust the data structure retrieved from an ORM query involving four tables. The product and category tables have a many-to-many relationship, with the product_category table serving as a bridge. Additionally, there's a fourth tabl ...