I am calling an API endpoint for a backend microservice that downloads an HTML file as the API data response. I'm using ReactJS and the Axios library to call the backend microservice, and I am getting a good response.
In the .then block of my code I am using a JavaScript Blob to handle the response data and save it as a HTML file. This block of the code basically takes the response from the API call and prepares the data as a downloadable link with a custom filename.
The download starts automatically when the link.click() portion of the block is executed.
However, the problem I encounter is the response is making my web browser download the same HTML file two times.
I am trying to figure out how to have the file download only once and NOT multiple times.
Here is my code:
const callAPI = () => {
Axios.post(api_endpoint, bodyArgs)
.then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", `${company}_${startDate}_${endDate}.html`);
document.body.appendChild(link);
link.click();
})
.catch(function (error) {
console.log(error);
alert(
"Sorry, there was an error processing your request. Please check the dates of your report and try again!"
);
});
};
Is there a problem in the .then block of my code, or is this a web browser specific issue? Any help is greatly appreciated. Thanks.
I think the click event fires twise
try
const callAPI = () => {
Axios.post(api_endpoint, bodyArgs)
.then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", `${company}_${startDate}_${endDate}.html`);
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(url);
link.remove();
})
.catch(function (error) {
console.log(error);
alert(
"Sorry, there was an error processing your request. Please check the dates of your report and try again!"
);
});
};
I figured out that I had my callAPI function written twice in my code. I have a Form component that has an onSubmit prop, and in that prop I have a handleSubmit function executes my callAPI() function.
I also have a Button component nested in my Form component that has a onSubmit prop that fired callAPI(). Therefore, whenever I clicked the button, the callAPI function was triggered twice...once through the Form component, and another through the Button component.
I removed the onSubmit prop in my Button component, and just let my Form component handle the submit action, and that solved my issue.