October 3, 2021 | 5 minutes read
1. Embed the link of the file to be downloaded on tag, and download the file in the new tab.
The above approach works fine for simpler use cases when the file being served is public and can be accessed by the whole world.
But what if the file is behind some kind authentication and can only be called via API by providing necessary authentication details (like bearer token in request authorization header).
This will result in error when downloading the file, and you’ll find the backend error shown on the UI.
Error while downloading file since authentication details were not provided
2. Call the API
To overcome the issue faced in approach one, we’ll have to access the file by calling the API. In the API request we can additionally provide necessary details to make the backend application aware that we have access to the requested file.
This is the approach we are going to discuss, i.e., call the API, get the data download this data as a file on the browser.
npx create-react-app react-download-file-axios –template typescript
2. Install helper libraries
npm i axios @types/axios luxon @types/react bootstrap react-bootstrap
A simple reusable component for a button which can handle state for loading when calling the API.
src/customHooks/useDownloadFile.ts
Let’s go through this function now.
The hook accepts various parameters:
<a />
tag in the parent component.preDownloading
function.onError
function will be invoked to handle the error.<a href... />
.<a />
in the DOM to download the file.postDownloading
function.src/components/downloadSampleCsvFile/index.tsx
There are two state variables to maintain state of the button, and show alert in case of error while calling API.
To the useDownloadHook custom hook various functions are passed:
Then the component returns the JSX:
Different Button States
3. < Alert /> : responsible for showing error message on the UI
Alert when calling API results in error.
Finally integrate <DownloadSampleCsv />
component to <App />
npm start / yarn start
Discover the common challenges and pitfalls encountered when evolving Kafka event schemas through a practical scenario.
MongoDB, a leader among NoSQL databases, offers robust features for managing and querying geospatial data. One of its most powerful tools is geo-indexing, which facilitates efficient querying of location-based data.
Detailing our experience and learnings by implementing sharding to horizontally scale a time series database with terabytes of data.