'How to download excel file from API in React?

I have excel file coming from API and I intend to implement a download button for users to click and download the file.


import FileDownload from "js-file-download";



function Download() {
 
  const [facilityName, setFacilityName] = useState("");

 
  const handleClick = (e) => {
    e.preventDefault()
   
  
   Axios({
     url: `apiEndpoint/${facilityName}`,
     method: "POST",
     responseType:"blob",
     
   }).then((res)=>{
     console.log("myres", res)
     FileDownload(res.data, `${facilityName}.xlsx`)
   })
  }

  return (
    <div>
         
        <TextField
          className="box"
          name="facility_name"
          select
          required
          value={facilityName}
          onChange={(e) => setFacilityName(e.target.value)}
        />
         
        <Button onClick={(e) => handleClick(e)}>
          Download File
        </Button>

    </div>
  );
}

export default Download;

When I click the download button, the file downloaded as excel but when I open the file, it reads "There was a problem with the content in filename.xlsx and so on". I have to download other excel file by change the {facility} var on the API and still got same error msg, only a blank page.

please i'm confused at this point, what am I missing in order to get the content of the file properly.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source