Skip to content

Instantly share code, notes, and snippets.

@imbudhiraja
Created May 6, 2021 11:45
Show Gist options
  • Save imbudhiraja/ca048a52963c2f05528042c730253e81 to your computer and use it in GitHub Desktop.
Save imbudhiraja/ca048a52963c2f05528042c730253e81 to your computer and use it in GitHub Desktop.
File downloader with redux-saga and ReactJS
import { createAction } from 'redux-actions';
export const DOWNLOAD_FILE = 'DOWNLOAD_FILE';
export const downloadFile = createAction(DOWNLOAD_FILE);
export const DOWNLOAD_FILE_FAILURE = 'DOWNLOAD_FILE_FAILURE';
export const downloadFileFailure = createAction(DOWNLOAD_FILE_FAILURE);
export const DOWNLOAD_FILE_REQUESTED = 'DOWNLOAD_FILE_REQUESTED';
export const downloadFileRequested = createAction(DOWNLOAD_FILE_REQUESTED);
export const DOWNLOAD_FILE_SUCCESS = 'DOWNLOAD_FILE_SUCCESS';
export const downloadFileSuccess = createAction(DOWNLOAD_FILE_SUCCESS);
import { all, call, put, takeLatest } from 'redux-saga/effects';
import { DOWNLOAD_FILE, downloadFileFailure, downloadFileRequested, downloadFileSuccess } from './file-downloader-action-types';
import httpClient from './http-client';
export function* downloadFileHandler({ payload }) {
yield put(downloadFileRequested());
const request = {
method: 'GET',
responseType: 'blob',
url: payload.url,
};
const {
data, error,
} = yield call(httpClient, request);
if (error) {
yield put(downloadFileFailure(error));
} else {
const url = window.URL.createObjectURL(new Blob([data]));
const link = document.createElement('a');
link.setAttribute('download', payload.filename);
link.href = url;
document.body.appendChild(link);
link.click();
yield put(downloadFileSuccess());
}
}
function* FileDownloader() {
yield all([
takeLatest(DOWNLOAD_FILE, downloadFileHandler),
]);
}
export default FileDownloader;
import React from 'react';
import ReactDOM from 'react-dom';
import { downloadFile } from './file-downloader-action-types';
const ReactAPP = () => {
const onExcelExport = () => {
const request = {
filename: 'student-list.xlsx',
url: 'student-export',
};
dispatch(downloadFile(request));
};
return (
<div role='presentation' className="mb-3 card" onClick={onExcelExport}></div>
);
};
const element = document.querySelector('#app');
ReactDOM.render(<ReactAPP />, element);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment